如何将从UIImagePickerController拍摄的图片保存为HEIF文件?

4

我如何将从UIImagePickerController获得的图片处理为HEIF文件?现在,使用相机作为源类型,UIImagePickerControllerOriginalImage仅提供UIImage。我想以HEIF格式将图像发送到服务器。假设已将imageExportPreset设置为当前值。

2个回答

4

我想对sverin的解决方案进行调整,不要使用ctx.workingColorSpace,因为这可能会改变图像实际所在的空间。例如,如果您将图像重新加载到UIImageView中并且它显示出被冲洗了的外观,则可能会注意到这一点。

同时更新了Swift 4版本。

do {

    let ctx = CIContext()
    let ciImage = CIImage(image: uiImage)
    try ctx.writeHEIFRepresentation(of: ciImage!, to: url, format: .RGBA8, colorSpace: ciImage.colorSpace!, options: [:])

} catch {
    print("ERROR", error.localizedDescription)
}

1

这是一个老问题,但根据你如何发送数据,你有两个选项。

  1. Write the UIImage to a physical file and send it.

    do {
    
        let ctx = CIContext()
        let ciImage = CIImage(image: uiImage)
        try ctx.writeHEIFRepresentation(of: ciImage!, to: url, format: kCIFormatRGBA8, colorSpace: ctx.workingColorSpace!, options: [:])
    
    } catch {
        print("ERROR", error.localizedDescription)
    }
    
  2. Write the UIImage to Data and send that

    let ctx = CIContext()
    let ciImage = CIImage(image: uiImage)
    let data = ctx.heifRepresentation(of: ciImage!, format: kCIFormatRGBA8, colorSpace: ctx.workingColorSpace!, options: [:])
    

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接