mlidal
mlidal

Reputation: 1153

Convert HEIF photo to JPEG for uploading to backend

I'm maintaining an app for uploading photos from iPhone to a backend service. Currently this service doesn't support the new HEIF format, so is there any way to have the Photos framework convert the photo data to jpeg?

I use PHImageManager.requestImageData(for:options:resultHandler:) to retrieve a Data object from the image which I then upload to a REST API.

Upvotes: 8

Views: 4593

Answers (1)

mlidal
mlidal

Reputation: 1153

(new solution, the previous one didn't keep the EXIF information)

To get the image as a JPEG photo, with EXIF information, create a CIImage object from the HEIF image data and use CIContext.jpegRepresentation(of: to get the jpeg-encoded image as a Data object

let imageManager = PHImageManager.default()
var photo : PHAsset
var options : PHImageRequestOptions

imageManager.requestImageData(for: photo, options: options, resultHandler: {
                imageData,dataUTI,orientation,info in
let ciImage = CIImage(data: imageData!)
if #available(iOS 10.0, *) {
    data = CIContext().jpegRepresentation(of: ciImage!, colorSpace: CGColorSpaceCreateDeviceRGB())!
    // upload image data
}

Upvotes: 12

Related Questions