如何在不丢失 exif 数据的情况下将 UIImage 转换为 JPEG?

Posted

技术标签:

【中文标题】如何在不丢失 exif 数据的情况下将 UIImage 转换为 JPEG?【英文标题】:How to convert UIImage to JPEG without loosing exif data? 【发布时间】:2020-03-10 13:46:48 【问题描述】:

我目前正在开发 ios 应用程序,我正在使用多部分图像上传将图像上传到服务器。以下是我的图片上传方法。

func uploadImageData(imageType:Int, uploadId:String, fileName:String, imageFile:UIImage, completion:@escaping (APIResponseStatus, ImageUploadResponse?) -> Void) 

        let image = imageFile
        let imgData = image.jpegData(compressionQuality: 0.2)!

        let params = [APIRequestKeys.imageType:imageType, APIRequestKeys.uploadId:uploadId, APIRequestKeys.fileName:fileName] as [String : Any]
        //withName is the post request key for the image file
        Alamofire.upload(multipartFormData:  (multipartFormData) in
            multipartFormData.append(imgData, withName: APIRequestKeys.imageFile, fileName: "\(fileName).jpg", mimeType: "image/jpg")
                for (key, value) in params 
                    multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key)
                
        , to: Constants.baseUrl + APIRequestMetod.uploadImageData, headers:self.getImageUploadHeaders())
             (result) in
                switch result 
                case .success(let upload, _, _):
                    APIClient.currentRequest = upload
                    upload.uploadProgress(closure:  (progress) in
                    )
                    upload.responseObject 
                        (response:DataResponse<ImageUploadResponse>) in
                        switch response.result 
                        case .success(_):
                            completion(APIClient.APIResponseStatus(rawValue: (response.response?.statusCode)!)!, response.value!)
                        case .failure(let encodingError):
                            if let err = encodingError as? URLError, err.code == .notConnectedToInternet 
                                completion(APIClient.APIResponseStatus.NoNetwork, nil)
                             else 
                                completion(APIClient.APIResponseStatus.Other, nil)
                            
                        
                    
                case .failure( _):
                    completion(APIClient.APIResponseStatus.Other, nil)
                
            
        

但是对于这个实现服务器总是发送exif数据错误。以下是我遇到的错误。

exif_read_data(A029C715-99E4-44BE-8691-AA4009C1F5BD_FOTOPREGUNTA.ico): Illegal IFD size in
upload_image_xhr.php on line

重要的是该服务在 POSTMAN 和 android 应用程序中也能正常工作。此错误仅适用于我的 iOS 实现。我的后端开发人员告诉我,我发送的数据中存在 exif 数据错误,请从我这边验证数据。 有人对此有任何想法吗? 提前致谢。

【问题讨论】:

【参考方案1】:

我将为使用 Multipart 将图像上传到服务器制作块功能

//Here strUrl = YOUR WEBSERVICE URL
//postParam = post Request parameter i.e. 
//let postParam : [String : Any] = [first_name : "name"]
//imageArray = image upload array i.e.
//var imageArray : [[String:Data]] = [["image_name" : YOUR IMAGE DATA]]

func postImageRequestWithURL(withUrl strURL: String,withParam postParam: Dictionary<String, Any>,withImages imageArray:[[String:Data]], completion:@escaping (_ isSuccess: Bool, _ response:NSDictionary) -> Void)

    let requetURL = strURL

    Alamofire.upload(multipartFormData:  (MultipartFormData) in

        for (imageDic) in imageArray
        
            for (key,valus) in imageDic
            
                MultipartFormData.append(valus, withName:key,fileName: "file.jpg", mimeType: "image/jpg")
            
        

        for (key, value) in postParam
        
            MultipartFormData.append("\(value)".data(using: .utf8)!, withName: key)

          // MultipartFormData.append(value, withName: key)
        

    , usingThreshold: UInt64.init(), to: requetURL, method: .post, headers: ["Accept": "application/json"])  (result) in

        switch result 
        case .success(let upload, _, _):

            upload.uploadProgress(closure:  (progress) in
                print("Upload Progress: \(progress.fractionCompleted)")
            )

            upload.responseJSON  response in

                let desiredString = NSString(data: response.data!, encoding: String.Encoding.utf8.rawValue)

                print("Response ====================")

                print(desiredString!)

                if let json = response.result.value as? NSDictionary
                
                    if response.response?.statusCode == 200
                        || response.response?.statusCode == 201
                        || response.response?.statusCode == 202
                    
                        completion(true,json);
                    
                    else
                    
                        completion(false,json);
                    
                
                else
                
                    completion(false,[:]);
                
            

        case .failure(let encodingError):
            print(encodingError)

            completion(false,[:]);
        

    

我希望这会有所帮助...

【讨论】:

以上是关于如何在不丢失 exif 数据的情况下将 UIImage 转换为 JPEG?的主要内容,如果未能解决你的问题,请参考以下文章

如何在不丢失 Xampp 中的数据的情况下将类型从 varchar 更改为 Date

如何在不丢失值的情况下将 json 解析为 pandas 数据框? [复制]

如何在不丢失小数的情况下将数据框中的字符转换为数字

如何在不丢失数据点顺序的情况下将 Pandas 中的字符串列表分解为单个列表

如何在不丢失信息的情况下将因子转换为整数\数字?

如何在不丢失 swift 精度的情况下将 String 转换为 Double [重复]