iOS技术专题

iOS高效图片压缩:HEIC图像压缩

2020-03-18  本文已影响0人  DearDan_f92e

前言:
HEIF(即高效图像文件格式)是一种新的图像文件格式,在许多方面都比其JPEG更好。该格式由MPEG在2013年开发,声称保存的数据量是JPEG的两倍,并且支持多种类型的图像数据。

extension UIImage {
  enum HEICError: Error {
    case heicNotSupported
    case cgImageMissing
    case couldNotFinalize
  }
  //接口iOS4+。 其中 .heic 要求 iOS11+,
  func heicData(compressionQuality: CGFloat) throws -> Data {
    //1.一个空的数据缓冲区.装图片数据,并创建压缩目标。设置为.heic
    let data = NSMutableData()
    guard let imageDestination =
      CGImageDestinationCreateWithData(
        data, AVFileType.heic as CFString, 1, nil
      )
      else {
        throw HEICError.heicNotSupported
    }
    //2.确保有要处理的图像数据
    guard let cgImage = self.cgImage else {
      throw HEICError.cgImageMissing
    }
    //3.质量控制。
    let options: NSDictionary = [
      kCGImageDestinationLossyCompressionQuality: compressionQuality
    ]
    //4.将图像数据和选项一起应用到目标,完成HEIC图像压缩。
    CGImageDestinationAddImage(imageDestination, cgImage, options)
    guard CGImageDestinationFinalize(imageDestination) else {
      throw HEICError.couldNotFinalize
    }
    
    return data as Data
  }
}

再来说说比JPEG 的好处:

上一篇下一篇

猜你喜欢

热点阅读