如何在 Swift 中将图像转换为渐进式 JPEG?

How can I convert image to progressive JPEG in Swift?

在我的项目中,我需要将任何格式的图像转换为渐进式 JPEG。我怎样才能做到这一点?

我这样试过,但是不行。

let sourceImage = UIImage(named: "example.jpg")
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as NSString
let url = CFURLCreateWithString(kCFAllocatorDefault,paths.stringByAppendingPathComponent("progressive.jpg") 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!)

由于错误定义 URL.The 出现问题,以下代码在 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!)