我正在使用UIImagePNGRepresentation
来保存图像。结果图像的大小为 30+ KB,这在我的情况下很大。
我尝试使用UIImageJPEGRepresentation
,它允许压缩图像,因此图像以 5KB 大小保存
如何使用UIImagePNGRepresentation
压缩图像大小?
PNG使用无损压缩,这就是为什么UIImagePNGRepresentation不像UIImageJPEGRepresentation那样接受compressionQuality
参数。使用不同的工具,您可能会获得较小的PNG文件,但与JPEG完全不同。
也许这会帮助你:
- (void)resizeImage:(UIImage*)image{
NSData *finalData = nil;
NSData *unscaledData = UIImagePNGRepresentation(image);
if (unscaledData.length > 5000.0f ) {
//if image size is greater than 5KB dividing its height and width maintaining proportions
UIImage *scaledImage = [self imageWithImage:image andWidth:image.size.width/2 andHeight:image.size.height/2];
finalData = UIImagePNGRepresentation(scaledImage);
if (finalData.length > 5000.0f ) {
[self resizeImage:scaledImage];
}
//scaled image will be your final image
}
}
调整图像大小
- (UIImage*)imageWithImage:(UIImage*)image andWidth:(CGFloat)width andHeight:(CGFloat)height
{
UIGraphicsBeginImageContext( CGSizeMake(width, height));
[image drawInRect:CGRectMake(0,0,width,height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext() ;
return newImage;
}