Two methods of image compression and compression to specified size in IOS development

Time:2021-2-27

///Compressed picture
+ (NSData *)imageCompressToData:(UIImage *)image{
  NSData *data=UIImageJPEGRepresentation(image, 1.0);
  if (data.length>300*1024) {
    if ( data.length >1024 * 1024) {// 1m and above
      data=UIImageJPEGRepresentation(image, 0.1);
    }else if (data.length>512*1024) {//0.5M-1M
      data=UIImageJPEGRepresentation(image, 0.5);
    }else if (data.length>300*1024) {//0.25M-0.5M
      data=UIImageJPEGRepresentation(image, 0.9);
    }
  }
  return data;
}

PS: let’s take a look at the image compression in IOS to the specified size

In IOS, in order to save memory, we need to process pictures to optimize the program and improve the efficiency of the program. Here is a method to reset the size of pictures according to our own requirements:

1、 There are two ways to compress a picture. The first is to compress the size of the picture and regenerate the size of the picture as follows

/** 
 *Compress the image to the specified size 
 * 
 *@ param image original image 
 *@ param size target size 
 * 
 *@ return generate image 
 */ 
-(UIImage *)compressOriginalImage:(UIImage *)image toSize:(CGSize)size{ 
  UIImage * resultImage = image; 
  UIGraphicsBeginImageContext(size); 
  [resultImage drawInRect:CGRectMake(00, 0, size.width, size.height)]; 
  UIGraphicsEndImageContext(); 
  return image; 
}

2、 The second is to modify the file size of the image: as follows

/** 
 *Compress the image to the specified file size 
 * 
 *@ param image target image 
 *@ param size target size (maximum) 
 * 
 *The image file returned by @ return 
 */ 
- (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{ 
  NSData * data = UIImageJPEGRepresentation(image, 1.0); 
  CGFloat dataKBytes = data.length/1000.0; 
  CGFloat maxQuality = 0.9f; 
  CGFloat lastData = dataKBytes; 
  while (dataKBytes > size && maxQuality > 0.01f) { 
    maxQuality = maxQuality - 0.01f; 
    data = UIImageJPEGRepresentation(image, maxQuality); 
    dataKBytes = data.length / 1000.0; 
    if (lastData == dataKBytes) { 
      break; 
    }else{ 
      lastData = dataKBytes; 
    } 
  } 
  return data; 
}

These are two ways to compress images.

summary

The above are the two methods of image compression and compression to a specified size introduced by Xiaobian to you. I hope they can help you. If you have any questions, please leave me a message and Xiaobian will reply you in time. Thank you very much for your support to developer!