2017-01-16 43 views
1

我需要使用swift 3.0將我的UIImage轉換爲漸進式jpeg。 我發現在迅速2.2以下代碼:在swift 3.0中將圖像轉換爲逐行JPEG

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

不過,這並不在SWIFT 3.0。 CGImageDestinationCreateWithURL給出錯誤(所有的CGImage類...)有什麼幫助?謝謝!

+0

「我發現下面的代碼」。不要使用你不明白的代碼。 – Sulthan

+0

謝謝你的幫助。對此,我真的非常感激! –

回答

1

阿譯斯威夫特3將與此類似:

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) 

不要忘了必要的模塊導入:

import UIKit 
import ImageIO 
import MobileCoreServices 
+0

謝謝!我剛纔發現我忘了導入這些模塊。 btw你知道這個代碼嗎?這段代碼是否會將「sourceImage」轉換爲具有數據的漸進式代碼? –

+0

@MarcIbrahim是的,壓縮比率爲60%。 – Sulthan