Search code examples
iosswiftuiimagejpegprogressive

Convert image to progressive JPEG in swift 3.0


I need to covert my UIImage to progressive jpeg using swift 3.0. I have found the following code in 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!)

But it doesn't work in swift 3.0. CGImageDestinationCreateWithURL gives an error.(all the CGImage classes...) Any help? Thanks!


Solution

  • A translation to Swift 3 would be similar to this:

    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)
    

    Don't forget the necessary module imports:

    import UIKit
    import ImageIO
    import MobileCoreServices