This code is not working anymore with iOS 17.5 Simulator:
import AVFoundation
extension UIImage {
enum HEICError: Error {
case heicNotSupported
case cgImageMissing
case couldNotFinalize
}
func heicData(compressionQuality: CGFloat) throws -> Data {
let data = NSMutableData()
guard let imageDestination =
CGImageDestinationCreateWithData(
data, AVFileType.heic as CFString, 1, nil
)
else {
throw HEICError.heicNotSupported
}
guard let cgImage = self.cgImage else {
throw HEICError.cgImageMissing
}
let options: NSDictionary = [
kCGImageDestinationLossyCompressionQuality: compressionQuality
]
CGImageDestinationAddImage(imageDestination, cgImage, options)
guard CGImageDestinationFinalize(imageDestination) else {
throw HEICError.couldNotFinalize
}
return data as Data
}
}
In case of an uncompressed heicData compressionQuality = 1 it wont return an image. it is producing this error instead:
writeImageAtIndex:962: *** CMPhotoCompressionSessionAddImage: err = kCMPhotoError_UnsupportedOperation [-16994] (codec: ‘hvc1’)