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

时间:2016-08-26 14:50:06

标签: ios swift image-processing core-graphics core-image

在我的项目中,我需要将任何格式的图像转换为渐进式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!)

1 个答案:

答案 0 :(得分:2)

由于URL定义不正确而出现问题。以下代码在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!)
相关问题