iOS image compression

Source: Internet
Author: User

In the development of iOS, often encounter such a problem, the image size is too large, or the file size is too large, you need to compress the picture, and then upload the server.
Of course, do not rule out some companies require the app to upload the original image, but this way too much traffic and time-consuming, if the network is not good, it is easy to upload the failure, which will lose some users.

1, understanding the concept:
1, "Pressure" refers to the size of the file is smaller, but the number of pixels unchanged, the length and width of the size of the same, then the quality may fall.
2, "shrinking" refers to the size of the file is smaller, that is, the number of pixels reduced, and the size of the long-width smaller, the file volume will also be reduced.
2, picture "Press" Processing:

For the "pressure" function, we can use the UIImageJPEGRepresentation or Uiimagepngrepresentation method, for example:

NSData *imgData = UIImageJPEGRepresentation(image, 0.5);

The first parameter is the picture object itself, the second parameter is the coefficient of pressure, and its value range is (0-1);
Official notes of UIImageJPEGRepresentation:

The quality of the resulting JPEG image, expressed as a value from 0.0 to 1.0. The value 0.0 represents the maximum compression (or lowest quality) while the value 1.0 represents the least compression (or best quality).

About PNG and JPEG format compression:

1. The UIImageJPEGRepresentation function requires two parameters: a reference to a picture and a compression factor, and uiimagepngrepresentation only requires a picture reference as an argument.
2.UIImagePNGRepresentation (UIImage *image) is much larger than the amount of image data returned by uiimagejpegrepresentation (uiimage* image, 1.0)

Before uploading the pictures in the project, the PNG size of the same picture was tested at 8M, while the JPG compression factor was 0.75, and the size was only 1 m. Also, reducing the compression factor does not have much effect on the picture visually.
Friendly tips:

Compression coefficient should not be too low, usually 0.3~0.7, too small may appear black edge, etc.
3, picture "shrink" Processing:

mainly through [image drawinrect:cgrectmake (0, 0, Targetwidth, targetheight)]; Realize.

/***  1, scale the picture by the maximum edge of the picture * *   @param image   Picture *   @param the longer side of the MaxSize picture (width/height) * *   @return &NB Sp       equal to scaled picture */-(UIImage *) Scaleimage: (UIImage *) image maxSize: (cgfloat) maxSize {   nsdata * data = uiimagejpegrepresentation (image, 1.0);    if (Data.length < * 1024x768) {//0.25m-0.5m (when picture is less than this range not compressed)        return image;   &NB SP;}    cgfloat imagewidth = image.size.width;    cgfloat imageheight = image.size.height;    cgfloat targetwidth = imagewidth;    cgfloat targetheight = imageheight;    cgfloat imagemaxsize = MAX (ImageWidth, imageheight);    if (Imagemaxsize > MaxSize) {       cgfloat scale = 0,       &NBSP;IF (ImageWidth >= ImageHeight) {//Width            scale = maxsize/imagewidth,            tar GetWidth = maxSize;            targetheight = imageheight * scale;       &NBSP;} else {//kao            scale = maxsize/imageheight;   & nbsp        targetheight = maxSize;            targetwidth = imagewidth * scale;        }        uigraphicsbeginimagecontext (Cgsizemake (Targetwidth, Targetheight));        [image drawinrect:cgrectmake (0, 0, Targetwidth, targetheight)];        uiimage *scaledimage = Uigraphicsgetimagefromcurrentimagecontext ();        uigraphicsendimagecontext ();        return scaledimage;    }    return image;}
  /***  2, picture support Zoom * *   @param image   Pictures *   @param maxSize zoom (usually between 0~1) * *   @return         equal to scaled picture */-(UIImage *) Scaleimag E: (UIImage *) image toscale: (float) scalesize {   uigraphicsbeginimagecontext (Cgsizemake (Image.size.width * Scalesize, Image.size.height * scalesize));    [image drawinrect:cgrectmake (0, 0, image.size.width * scalesize, Image.size.height * scalesize)];    uiimage *scaledimage = Uigraphicsgetimagefromcurrentimagecontext ();    uigraphicsendimagecontext ();    return scaledimage;}   

/** *  3, 等比缩放成自定长宽的图片 * *  @param image      源图片 *  @param targetSize 自定义目标图片的size * *  @return 处理后图片 */ - (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)targetSize {    UIGraphicsBeginImageContext(CGSizeMake(targetSize.width, targetSize.height));    [image drawInRect:CGRectMake(0, 0, targetSize.width, targetSize.height)];    UIImage *targetSizeImage = UIGraphicsGetImageFromCurrentImageContext();    UIGraphicsEndImageContext();    return targetSizeImage; }

We only "pressure" the picture and not shrink, sometimes it is not up to our needs. Therefore, to properly "shrink" the size of the picture, you can meet our needs.

  //Get the picture size (how many m) by the picture) method-(NSData *) ImageData: ( UIImage *) Image {   nsdata *data = uiimagejpegrepresentation (image, 1.0);    if (Data.length > 100 *1024) {       if (Data.length > 1024*1024) {//1m and above            dat A = uiimagejpegrepresentation (image, 0.1);        }else if (Data.length > 512*1024) {//0.5m-1m             &NBSP ;  data = uiimagejpegrepresentation (image, 0.5);        }else if (Data.length > 200*1024) {//0.25m-0.5m            dat A = uiimagejpegrepresentation (image, 0.9);        }    }    return data;}   

Verify:
Take the second green leaf picture of the simulator as an example
The original size is 24.9M, 4288 * 2848 pixels;
After one uiimagejpegrepresentation "pressure" treatment

UIImage *tmpImage = [UIImage imageWithContentsOfFile:photo.photoPath];NSData *imageData = UIImageJPEGRepresentation(tmpImage, 0.5);

The image size is 836.9K, 4288 * 2848 pixels;

After one uiimagepngrepresentation "pressure" treatment

UIImage *tmpImage = [UIImage imageWithContentsOfFile:photo.photoPath];NSData *imageData = UIImagePNGRepresentation(tmpImage);

Image size 24.9M, 4288 * 2848 pixels; almost unchanged.

Once the "shrink" processing (the author gives the maximum width of the picture is limited to 640 pixels)

UIImage *tmpImage = [UIImage imageWithContentsOfFile:photo.photoPath];tmpImage = [self scaleImage:tmpImage maxSize:640];

The image size is 795.9K, 640 * 426 pixels;

Once processed by "compression":

UIImage *tmpImage = [UIImage imageWithContentsOfFile:photo.photoPath];tmpImage = [self scaleImage:tmpImage maxSize:640];NSData *imageData = UIImageJPEGRepresentation(tmpImage, 0.5);

The image size is 698K, 640 * 426 pixels;
We can adjust the different parameters according to the actual situation to achieve their own project requirements.

iOS image compression

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.