我使用这个从服务器获取图像:
- (void)downloadImageWithURL:(NSURL *)url completionBlock:(void (^)(BOOL succeeded, NSData *data))completionBlock
{
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse *response, NSData *data, NSError *error)
{
if (!error)
{
completionBlock(YES, data);
}
else
{
completionBlock(NO, nil);
}
}];
}
哪个提供NSData。现在为了获得更好的性能,我想在jpeg
中显示图像。
我知道如何使用NSData to UIImag
转换UIImage *image=[UIImage imageWithData:data];
e
以及如何从图像NSData *imageData = UIImagePNGRepresentation(image);
但两者都没有做我需要的,我想从服务器获取NSData,并创建它的JPEG图像。我该怎么办? (我是否必须首先使用jpeg创建新数据,而不是使用此数据中的图像?)
答案 0 :(得分:3)
要将从服务器获取的数据转换为jpeg,请使用:
UIImage *image = [UIImage imageWithData:serverData];
NSData *jpegData = UIImageJPEGRepresentation(image, 0.75f);
答案 1 :(得分:1)
你可能需要这样做:
CGDataProviderRef imgProvider = CGDataProviderCreateWithCFData((CFDataRef) data);
CGImageRef imgRef = CGImageCreateWithJPEGDataProvider(imgProvider, NULL, true, kCGRenderingIntentDefault);
确保释放imgRef和imgProvider
答案 2 :(得分:0)
在Swift 5和iOS 12中,您可以使用CGImage
,CGImageDestination
和CGDataProvider
以便将某些JPEG图像数据写入给定的URL
。以下函数实现显示了如何执行此操作:
import Foundation
import ImageIO
import MobileCoreServices
func saveImageData(_ data: Data, to fileUrl: URL) {
guard let provider = CGDataProvider(data: data as CFData) else {
print("Could not create data provider from data")
return
}
guard let cgImage = CGImage(jpegDataProviderSource: provider, decode: nil, shouldInterpolate: true, intent: CGColorRenderingIntent.defaultIntent) else {
print("Could not create cgImage from provider")
return
}
guard let imageDestination = CGImageDestinationCreateWithURL(fileUrl as CFURL, kUTTypeJPEG, 1, nil) else {
print("Could not create an image destination from url")
return
}
let options = [
kCGImageDestinationLossyCompressionQuality: 0.75, // Compress quality (if required)
kCGImagePropertyOrientation: CGImagePropertyOrientation.right.rawValue // Rotate image to the right (if required)
] as CFDictionary
CGImageDestinationAddImage(imageDestination, cgImage, options)
let imageIsWritten = CGImageDestinationFinalize(imageDestination)
if !imageIsWritten {
print("Image could not be written")
}
}
用法:
let data: Data = …
let documentDirectoryUrl = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let fileUrl = documentDirectoryUrl.appendingPathComponent("image.jpeg")
saveImageData(data, to: fileUrl)
来源: -Image I/O Programming Guide - Working with Image Destinations