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

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

有什么错误吗?如果是常量,请查看我提出的类似问题的答案... http://stackoverflow.com/questions/38916484/cgimagedestinationcreatewithdata-constants-in-ios - Grimxn
不,它不会出错。常量没有问题。但问题是它没有输出。 - sant05
1
实际上,在测试您的代码时,我收到了一个错误消息:CGDataConsumer(url_close):写入失败。 - Eric Aya
@EricAya 你找到解决方案了吗? - sant05
不行,我尝试了几个选项但是无法让它工作。很奇怪,因为let done = CGImageDestinationFinalize(destinationRef!); print(done)打印出了"true"。但是什么都没有被写入,而且错误信息弹出了。 - Eric Aya
@EricAya 谢谢你的帮助。如果我们无法写入文件,你能否编写代码使我们能够上传到服务器? - sant05
1个回答

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!)

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