在 swift 3.0 中将图像转换为渐进式 JPEG

Convert image to progressive JPEG in swift 3.0

我需要使用 swift 3.0 将我的 UIImage 转换为渐进式 jpeg。 我在 swift 2.2 中找到了以下代码:

    let sourceImage = UIImage(named: "example.jpg")
let path = (NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString).stringByAppendingPathComponent("progressive.jpg")
let fileUrl = NSURL(fileURLWithPath: path as String, isDirectory: true)
let url = CFURLCreateWithString(kCFAllocatorDefault,fileUrl.absoluteString as CFString  , nil)
let destinationRef = CGImageDestinationCreateWithURL(url, kUTTypeJPEG, 1, nil)
let jfifProperties = NSDictionary(dictionary: [kCGImagePropertyJFIFIsProgressive:kCFBooleanTrue])
let properties = NSDictionary(dictionary: [kCGImageDestinationLossyCompressionQuality:0.6,kCGImagePropertyJFIFDictionary:jfifProperties])
CGImageDestinationAddImage(destinationRef!, (sourceImage?.CGImage)!, properties)
CGImageDestinationFinalize(destinationRef!)

但它在 swift 3.0 中不起作用。 CGImageDestinationCreateWithURL 给出错误。(所有 CGImage 类...)有帮助吗?谢谢!

Swift3 的翻译类似于:

guard let sourceImage = UIImage(named: "example.jpg") else {
    fatalError("Image could not be loaded")
}

let documentsUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
let targetUrl = documentsUrl.appendingPathComponent("progressive.jpg") as CFURL

let destination = CGImageDestinationCreateWithURL(targetUrl, kUTTypeJPEG, 1, nil)!
let jfifProperties = [kCGImagePropertyJFIFIsProgressive: kCFBooleanTrue] as NSDictionary
let properties = [
    kCGImageDestinationLossyCompressionQuality: 0.6,
    kCGImagePropertyJFIFDictionary: jfifProperties
] as NSDictionary

CGImageDestinationAddImage(destination, sourceImage.cgImage!, properties)
CGImageDestinationFinalize(destination)

不要忘记必要的模块导入:

import UIKit
import ImageIO
import MobileCoreServices