我正在使用UIImagePNGRepresentation
来保存一张图片,结果的图片大小超过了30 KB,在我的情况下这是个很大的文件。
我尝试使用UIImageJPEGRepresentation
来压缩图片,它可以让图像保持在小于5KB的大小,这非常好,但是用JPEG保存会给它一个白色背景,而我不想要(我的图片是圆形的,所以我需要保存它的透明背景)。
如何使用UIImagePNGRepresentation
来压缩图像大小?
我正在使用UIImagePNGRepresentation
来保存一张图片,结果的图片大小超过了30 KB,在我的情况下这是个很大的文件。
我尝试使用UIImageJPEGRepresentation
来压缩图片,它可以让图像保持在小于5KB的大小,这非常好,但是用JPEG保存会给它一个白色背景,而我不想要(我的图片是圆形的,所以我需要保存它的透明背景)。
如何使用UIImagePNGRepresentation
来压缩图像大小?
也许这会对你有所帮助:
- (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;
}
UIImagePNGRepresentation
返回图像最小可能的压缩大小,由于这是一种无损压缩方法,它不会像JPEG那样影响图像质量。因此,唯一的可能性就是减小图像尺寸。 - Ayan SenguptaUIImage
转换为RGB数据,然后尝试使用不同的PNG编码器,例如libpng。最终结果取决于您拥有的图像。 - SulthanUIImagePNGRepresentation
来减小图像大小,而我们绝对不能使用该API来做到这一点。显然有一些第三方API可用于替代。不幸的是,本地的UIImagePNGRepresentation
已经尽力了:( - Ayan Sengupta