iOS compress image from nsdata
I have an application that downloads jpeg images, but they're large, larger than necessary for the application. I've created a class that'll download the NSData of the image. What's the best way to take the NSData and compress the image.
开发者_StackOverflow中文版So far the only route i've seen is to write the image to disk temporarily, access it and compress the jpeg on disk.
Is there an alternative way where you don't have to write to disk and compress it directly and the data is received?
It would be better to compress the image before your application downloads it. However, if this is beyond your control, compress them after.
To convert an image to another format you can use functions defined in CGImageDestination.h
I would make a function of class method that converts a given image:
+ (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;
}
The image type can be kUTTypePNG, but the quality parameter most likely will not work. It also can be kUTTypeJPEG2000 for your needs.
You can initialise a new image with the data or save it to disk.
If you're asking what I think you're asking, you can create UIImage objects with a chunk of NSData using +imageWithData:
.
NSData *imageData = // Get the image data here
UIImage *image = [UIImage imageWithData:data];
精彩评论