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

时间:2017-01-16 16:31:47

标签: ios swift uiimage jpeg progressive

我需要使用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类......)任何帮助?谢谢!

1 个答案:

答案 0 :(得分:1)

Swift 3的翻译类似于:

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