iosphotosframeworkheif

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.


Solution

  • (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
    }