How can I convert image to progressive JPEG in Swift?
Asked Answered
C

1

6

In my project I need to convert images of any format to progressive JPEG. How can I achieve that?

I tried like this but it does not work.

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!)
Camillacamille answered 26/8, 2016 at 14:50 Comment(6)
What's the error? If it is the constants, check out this answer to a similar question I asked... #38916984Higgins
No it does not give error. There is no problem with constants. But problem is it does not give output.Camillacamille
Actually I get an error message when testing your code: CGDataConsumer(url_close): write failed.Lorenzetti
@EricAya Did you find the solution?Camillacamille
Nope, I tried several options but I can't make this work. It's weird because let done = CGImageDestinationFinalize(destinationRef!); print(done) prints "true". But nothing is written and the error message pops up.Lorenzetti
@EricAya Thank you for your help. If we can not write the file, can you make the code such that we will be able to upload to the server?Camillacamille
C
2

There was a problem because of incorrectly defined URL.The following code works successfully on 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!)
Camillacamille answered 27/8, 2016 at 16:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.