2017-01-16 6 views
1

swift 3.0を使用してUIImageをプログレッシブJPEGに変換する必要があります。私は、SWIFT 2.2で次のコードを発見した :スウィフト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

関連する問題