11

UIImagePNGRepresentation用来保存图像。结果图像大小为 30+ KB,在我的情况下这是很大的。

我尝试使用UIImageJPEGRepresentation它,它允许压缩图像,所以图像保存在 < 5KB 大小,这很棒,但是将它保存为 JPEG 会得到白色背景,这是我不想要的(我的图像是圆形的,所以我需要保存它具有透明背景)。

如何压缩图像大小,使用UIImagePNGRepresentation

4

2 回答 2

2

PNG 使用无损压缩,这就是 UIImagePNGRepresentationcompressionQuality不像 UIImageJPEGRepresentation 那样接受参数的原因。您可能会使用不同的工具获得更小的 PNG 文件,但与 JPEG 不同。

于 2016-02-11T19:46:33.733 回答
0

可能这会帮助你:

- (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;
}
于 2016-02-11T19:54:59.203 回答