1

I'm using Alamofire to upload files. It's okay to handle jpeg and png images with UIImage[JPEG|PNG]Representation(), but how to convert animated gif files to NSData?

I tried AnimatedGIFImageSerialization but it's so old and does not work. How to convert animated Gif UIImage to NSData for Alamofire?

 func uploadFile() {
    if let fileURL = NSBundle.mainBundle().URLForResource("AarioAi", withExtension: "jpeg"){
        var imageData : NSData? = nil
        if let image = UIImage(named: "loading2.gif") {
            let filetype = "gif"
            switch filetype {
            case "jpeg", "jpg":
                imageData = UIImageJPEGRepresentation(image, 1.0)
            case "gif":
                imageData = UIImagePNGRepresentation(image)
            case "png":
                imageData = UIImagePNGRepresentation(image)
            default:
                imageData = UIImagePNGRepresentation(image)
            }
        }

    Alamofire.upload(.POST, Conf.URL.uploadFile, multipartFormData: {
        // POST file[]=xxxx&&file[]=xxxxx
        multipartFormData in
        multipartFormData.appendBodyPart(fileURL: fileURL, name: "file[]")
        multipartFormData.appendBodyPart(data: imageData!, name: "file[]", fileName: "loading2.gif", mimeType: "image/gif")

        },
        encodingCompletion: {
            encodingResult in
            switch encodingResult {
            case .Success(let upload, _, _):
                upload.responseJSON { response in
                    debugPrint(response)
                }
            case .Failure(let encodingError):
                print(encodingError)
            }
    })
    }
}
Lou Franco
  • 87,846
  • 14
  • 132
  • 192
AarioAi
  • 563
  • 1
  • 5
  • 18

1 Answers1

0

The key is to not make a UIImage from a file in the first place. When you write code like this:

UIImage(named: "loading2.gif")

You are decoding the file into a format that can be shown on the screen. Also, a UIImage can only represent a single frame of the GIF. Even for JPEGs, where it looks like it works, you are losing all of the meta-data and probably losing quality by re-encoding. Not to mention, it's a lot slower to decode and re-encode than just send the file directly.

Instead of doing that, just load the file contents directly into an NSData object by following the instructions here:

Convert Gif image to NSData

Community
  • 1
  • 1
Lou Franco
  • 87,846
  • 14
  • 132
  • 192