【发布时间】:2011-09-13 21:35:55
【问题描述】:
我有一个下载 jpeg 图像的应用程序,但它们很大,超出了应用程序所需的大小。我创建了一个类来下载图像的 NSData。获取 NSData 并压缩图像的最佳方法是什么。
到目前为止,我看到的唯一途径是将图像临时写入磁盘,访问它并压缩磁盘上的 jpeg。
是否有另一种方法,您不必写入磁盘并直接压缩它并接收数据?
【问题讨论】:
标签: objective-c ios uiimage jpeg nsdata
我有一个下载 jpeg 图像的应用程序,但它们很大,超出了应用程序所需的大小。我创建了一个类来下载图像的 NSData。获取 NSData 并压缩图像的最佳方法是什么。
到目前为止,我看到的唯一途径是将图像临时写入磁盘,访问它并压缩磁盘上的 jpeg。
是否有另一种方法,您不必写入磁盘并直接压缩它并接收数据?
【问题讨论】:
标签: objective-c ios uiimage jpeg nsdata
最好在应用程序下载之前压缩图像。但是,如果这超出了您的控制范围,请在之后压缩它们。
要将图像转换为另一种格式,您可以使用 CGImageDestination.h 中定义的函数
我会创建一个转换给定图像的类方法函数:
+ (NSData*)imageDataWithCGImage:(CGImageRef)CGimage UTType:(const CFStringRef)imageUTType desiredCompressionQuality:(CGFloat)desiredCompressionQuality
{
NSData* result = nil;
CFMutableDataRef destinationData = CFDataCreateMutable(kCFAllocatorDefault, 0);
CGImageDestinationRef destinationRef = CGImageDestinationCreateWithData(destinationData, imageUTType, 1, NULL);
CGImageDestinationSetProperties(destinationRef, (CFDictionaryRef)[NSDictionary dictionaryWithObjectsAndKeys:[NSNumber numberWithFloat:desiredCompressionQuality], (NSString*)kCGImageDestinationLossyCompressionQuality, nil]);
if (destinationRef != NULL)
{
CGImageDestinationAddImage(destinationRef, CGimage, NULL);
if (CGImageDestinationFinalize(destinationRef))
{
result = [NSData dataWithData:(NSData*)destinationData];
}
}
if (destinationData)
{
CFRelease(destinationData);
}
if (destinationRef)
{
CFRelease(destinationRef);
}
return result;
}
图像类型可以是 kUTTypePNG,但质量参数很可能不起作用。根据您的需要,它也可以是 kUTTypeJPEG2000。
您可以使用数据初始化新图像或将其保存到磁盘。
【讨论】:
如果你问我认为你在问什么,你可以使用 +imageWithData: 创建带有一大块 NSData 的 UIImage 对象。
NSData *imageData = // Get the image data here
UIImage *image = [UIImage imageWithData:data];
【讨论】: