HEIC Image Compression for iOS | Kodeco

In this HEIC image compression tutorial, you’ll learn how to transform images into HEIC and JPEG formats, comparing their efficiency for optimum performance.


This is a companion discussion topic for the original entry at https://www.kodeco.com/4726843-heic-image-compression-for-ios

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’)