2

Given Data and its UTI, what's the proper way to convert it to JPEG?

PHImageManager.default().requestImageData(for: asset, options: options, resultHandler: { (imageData: Data?, dataUTI: String?, _, _) in  
    guard let imageData = imageData, let dataUTI = dataUTI else { return }  
    if !UTTypeConformsTo(dataUTI as CFString, kUTTypeJPEG) {  
        //TODO: Convert to JPEG  

    }  
}) 
kintan
  • 19
  • 1
  • 3

2 Answers2

3

Just had this issue with the PHImageManager returning the data as .heic instead .jpeg, this worked for me:

PHImageManager.default().requestImageData(for: asset, options: PHImageRequestOptions(), resultHandler: { (data, string, orient, info) in
    if string?.range(of: ".heic") != nil || string?.range(of: ".heif") != nil {
        let rawImage = UIImage(data: data!)
        self.uploadData = UIImageJPEGRepresentation(rawImage!, 1.0)
        self.uploadName = "public.jpeg"
    } else {
        self.uploadData = data
        self.uploadName = string
    }
    self.uploadFileToServer()
})
Asleepace
  • 3,466
  • 2
  • 23
  • 36
2

If it's UTType is JPEG, you already have a proper JPEG encoded representation of the image. And if you want to display that image to your screen, you only need to initialize a UIImage object with the given data calling init?(data:) initializer.

Vahan Babayan
  • 723
  • 7
  • 21
  • the UTType is HEIC. I want to turn HEIC into JPEG。 – kintan Jul 10 '17 at 03:25
  • 2
    You can ignore new high efficiency formats like `HEIC`, on the [WWDC](https://developer.apple.com/videos/wwdc2017/) Apple introduced them and promised that they will be automatically converted to more common `JPEG` format when it needed. However if you need to convert a `HEIC` encoded data to `JPEG` I would suggest you to create a `UIImage` with that data and use `UIImageJPEGRepresentation(_:_:)` function to encode it as `JPEG`. – Vahan Babayan Jul 10 '17 at 07:30
  • thank. the phasset no automatically converted to more common JPEG format. – kintan Jul 11 '17 at 03:12
  • @kintan were you able to convert to jpeg data in PHAsset? – hacker_1989 Oct 13 '17 at 00:13