iosalamofireimgur

Why imgur adds white background to some png images, and to others not with Alamofire and Swift?


This is how I simply upload images to Imgur using Alamofire and Swift:

let url = URL(string: "https://api.imgur.com/3/upload")!
private var headers: [String: String] {
    ["X-Token": "[mytokenhere]", "Authorization": "Client-ID [myidhere]"]
}

Alamofire.upload(multipartFormData: { multipart in
    if let data = UIImagePNGRepresentation(image.image) {
         multipart.append(data, withName: "image", fileName: "image.png", mimeType: "image/png")
    }
}, to: url, headers: headers, encodingCompletion: { result in
    //convert result image from result here
})

Example before upload, original image (as you can see, it adds white background even here on SO, why?):

enter image description here

And after upload, returned url to an uploaded image:

enter image description here

Originally on computer and iPhone it look like this:

enter image description here


Solution

  • This is how Imgur behaves when your image size exceeds a limit - it converts your image into a JPEG. See the Imgur Help page on upload limits.

    The maximum file size for non-animated images (think JPG, PNG, etc) is 20MB. PNG files over 5MB will be converted to JPEGs.

    Note that for anonymous uploads, this limit is 1MB:

    Non-animated images over 1MB for anonymous uploads and 5MB for account holders will be lossily compressed.

    You can see that it has been turned into a JPEG by inspecting the response JSON. The "type" key would indicate the type of image actually uploaded. For example, this is returned when I anonymously uploaded a png larger than 1MB:

    {
        "status": 200,
        "success": true,
        "data": {
            ...
            "type": "image/jpeg", // <---
            ...
        }
    }