How to compress image size using UIImagePNGRepresentation

I'm using UIImagePNGRepresentation to save an image. The result image is of size 30+ KB and this is BIG in my case.

I tried using UIImageJPEGRepresentation and it allows to compress image, so image saves in < 5KB size, which is great, but saving it in JPEG gives it white background, which i don't want (my image is circular, so I need to save it with transparent background).

How can I compress image size, using UIImagePNGRepresentation ?


PNG uses lossless compression, that's why UIImagePNGRepresentation does not accept compressionQuality parameter like UIImageJPEGRepresentation does. You might get a bit smaller PNG file with different tools, but nothing like with JPEG.


May be this will help you out:

- (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
    }
}

Resizing 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;
}
链接地址: http://www.djcxy.com/p/32192.html

上一篇: 使用Amazon SNS,SQS和PHP推送消息

下一篇: 如何使用UIImagePNGRepresentation压缩图像大小