【问题标题】:How can I convert image to progressive JPEG in Swift?如何在 Swift 中将图像转换为渐进式 JPEG?
【发布时间】:2017-01-03 07:00:13
【问题描述】:

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

【问题讨论】:

  • 错误是什么?如果是常量,请查看我提出的类似问题的答案...stackoverflow.com/questions/38916484/…
  • 不,它不会给出错误。常量没有问题。但问题是它没有输出。
  • 实际上我在测试您的代码时收到一条错误消息:CGDataConsumer(url_close): write failed.
  • @EricAya 你找到解决方案了吗?
  • 不,我尝试了几个选项,但我无法完成这项工作。这很奇怪,因为let done = CGImageDestinationFinalize(destinationRef!); print(done) 打印出“真”。但是什么都没写,就弹出错误信息。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2021-04-24
    • 2017-06-03
    • 1970-01-01
    • 2020-06-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-14
    相关资源
    最近更新 更多