Swift Library:如何将动画Gif UIImage转换为Alamofire的NSData?

时间:2016-03-23 12:13:35

标签: swift swift2 nsdata gif alamofire

我正在使用Alamofire上传文件。使用UIImage [JPEG | PNG] Representation()处理jpeg和png图像是可以的,但是如何将动画gif文件转换为NSData?

我试过了AnimatedGIFImageSerialization,但它太旧了,不起作用。 如何将动画Gif UIImage转换为Alamofire的NSData?

 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)
            }
    })
    }
}

1 个答案:

答案 0 :(得分:0)

关键是首先不要从文件中创建UIImage。当你编写这样的代码时:

UIImage(named: "loading2.gif")

您正在将文件解码为可在屏幕上显示的格式。此外,UIImage只能代表GIF的单个帧。即使对于看似有效的JPEG,你也会失去所有的元数据,并且可能会因重新编码而失去质量。更不用说,解码和重新编码比直接发送文件慢得多。

不要这样做,只需按照以下说明将文件内容直接加载到NSData对象中:

Convert Gif image to NSData