Today, I will show you how to upload an image anonymously from your phone’s Photo Library to imgur.com
On my demo app, at the end of this article, the user first chooses an image from the Photos app and then uploads it to imgur.com.
This tutorial only focuses on how to upload an image to imgur, not selecting an image from the Photo app.
As an example, we are going to upload the following image I found on the Internet 🐶
Getting the Client ID
As I said before, we’re going to upload an image anonymously, but imgur still wants to know from which app they’re coming from.
For that, we need to get a Client ID from their website.
Go to https://api.imgur.com/oauth2/addclient and create an imgur account, if you haven’t already.
Fill the required fields and press submit
Copy the Client ID somewhere. We’re gonna need it later.
Imgur has some limitations on how many uploads can get from a single app every day (approx. 1,250 uploads per day). You can read more about that here.
Creating the Image Uploader
Create a method uploadImageToImgur that takes an UIImage as a parameter.
func uploadImageToImgur(image: UIImage) {
// ...
}
Code language: Swift (swift)
Convert the image (UIImage) to Base64 text.
func uploadImageToImgur(image: UIImage) {
getBase64Image(image: image) { base64Image in
// ...
}
}
func getBase64Image(image: UIImage, complete: @escaping (String?) -> ()) {
DispatchQueue.main.async {
let imageData = image.pngData()
let base64Image = imageData?.base64EncodedString(options: .lineLength64Characters)
complete(base64Image)
}
}
Code language: Swift (swift)
Do an HTTP POST request, using URLSession, that takes as HTTP Header the Client ID we got before.
The form of the HTTP request is multipart/form-data.
So you need to pass the converted Base64 image into the HTTP body of the request.
let CLIENT_ID = "MY_CLIENT_ID"
func uploadImageToImgur(image: UIImage) {
getBase64Image(image: image) { base64Image in
let boundary = "Boundary-\(UUID().uuidString)"
var request = URLRequest(url: URL(string: "https://api.imgur.com/3/image")!)
request.addValue("Client-ID \(self.CLIENT_ID)", forHTTPHeaderField: "Authorization")
request.addValue("multipart/form-data; boundary=\(boundary)", forHTTPHeaderField: "Content-Type")
request.httpMethod = "POST"
var body = ""
body += "--\(boundary)\r\n"
body += "Content-Disposition:form-data; name=\"image\""
body += "\r\n\r\n\(base64Image ?? "")\r\n"
body += "--\(boundary)--\r\n"
let postData = body.data(using: .utf8)
request.httpBody = postData
// ...
}
}
Code language: Swift (swift)
This is how the JSON data looks like as a result after uploading successfully your image:
{
"data":{
"id":"EBJIeoZ",
"title":null,
"description":null,
"datetime":1582389917,
"type":"image/jpeg",
"animated":false,
"width":1667,
"height":2048,
"size":172036,
"views":0,
"bandwidth":0,
"vote":null,
"favorite":false,
"nsfw":null,
"section":null,
"account_url":null,
"account_id":0,
"is_ad":false,
"in_most_viral":false,
"has_sound":false,
"tags":[
],
"ad_type":0,
"ad_url":"",
"edited":"0",
"in_gallery":false,
"deletehash":"aCbT2JmYe6JYJp1",
"name":"",
"link":"https://i.imgur.com/EBJIeoZ.jpg"
},
"success":true,
"status":200
}
Code language: Kotlin (kotlin)
Parse the JSON data and get the link.
func uploadImageToImgur(image: UIImage) {
getBase64Image(image: image) { base64Image in
// ...
URLSession.shared.dataTask(with: request) { data, response, error in
if let error = error {
print("failed with error: \(error)")
return
}
guard let response = response as? HTTPURLResponse,
(200...299).contains(response.statusCode) else {
print("server error")
return
}
if let mimeType = response.mimeType, mimeType == "application/json", let data = data, let dataString = String(data: data, encoding: .utf8) {
print("imgur upload results: \(dataString)")
let parsedResult: [String: AnyObject]
do {
parsedResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String: AnyObject]
if let dataJson = parsedResult["data"] as? [String: Any] {
print("Link is : \(dataJson["link"] as? String ?? "Link not found")")
}
} catch {
// Display an error
}
}
}.resume()
}
}
Code language: Swift (swift)
Using the Image Uploader
In your ViewController swift file, use the method we made before by calling the uploadImageToImgur and passing the image (UIImage) you want to upload.
@IBAction func uploadImageButtonAction(_ sender: UIButton) {
uploadImageToImgur(image: selectedImage)
}
Code language: Swift (swift)
You can find the final project here
If you have any questions, please feel free to leave a comment below
Hello,
I’d like to publish an image on imgur but with my account, not in anonymous, where can i add the form parameters in your code ?
Thanks
First, the user must authorize your application (in this case, is you).
Add at the top of your file:
And then (as REDIRECT_URI, put the redirect URL you added when you were creating the Client ID):
This will show a WKWebView, after you login with your account, you have to “catch” the access token to use it later to upload the image through your account.
Add these lines at the bottom of your swift file:
Next, in the uploadToImgur method, change the line:
to this:
Note: This method is not fully completed (you need to manage the refresh tokens, save the access token so you don’t need to login every time e.t.c), but it’s working!
Maybe I’ll added it in this tutorial, with more details, in the future.
Ok thanks a lot ! And another question, when i publish image doing this they are publish hidden, do you know why ?
You can’t upload image and be in ‘publish’ state. You can do it when you login to your account and press the button ‘To Community‘.
To make the ‘To Community’ button available, you need to add a title in your post.
With the following code you can upload a image with a title:
I added a ‘privacy’ parameter and set it to ‘publish’, but it’s not working as I said.