我有一个下载 jpeg 图像的应用程序,但它们很大,比应用程序所需的大。我创建了一个将下载图像的 NSData 的类。获取 NSData 并压缩图像的最佳方法是什么。
到目前为止,我看到的唯一途径是将图像临时写入磁盘,访问它并在磁盘上压缩 jpeg。
有没有另一种方法,您不必写入磁盘并直接压缩它并接收数据?
最佳答案
最好在您的应用程序下载之前压缩图像。但是,如果这超出了您的控制范围,请在之后压缩它们。
要将图像转换为另一种格式,您可以使用 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 以满足您的需要。
您可以使用数据初始化新图像或将其保存到磁盘。
关于objective-c - iOS从nsdata压缩图片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7408841/