2017-01-16 3 views
1

Мне нужно скрыть мой UIImage до прогрессивного jpeg с помощью swift 3.0. Я нашел следующий код в стремительной 2.2:Преобразование изображения в прогрессивное JPEG в swift 3.0

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

Но это не работает в быстром 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

Спасибо! Я просто понял, что забыл импортировать эти модули. Кстати, вы поняли этот код? Преобразует ли этот код «sourceImage» в прогрессивный с его данными? –

+0

@MarcIbrahim Да, с коэффициентом сжатия 60%. – Sulthan

Смежные вопросы