///Compress the picture+ (NSData *)imageCompressToData:(UIImage *)image{ NSData *data=UIImageJPEGRepresentation(image, 1.0); if (>300*1024) { if (>1024*1024) {//1M and above data=UIImageJPEGRepresentation(image, 0.1); }else if (>512*1024) {//0.5M-1M data=UIImageJPEGRepresentation(image, 0.5); }else if (>300*1024) {//0.25M-0.5M data=UIImageJPEGRepresentation(image, 0.9); } } return data; }
ps: Let's take a look at the compression of the images in iOS to the specified size
In iOS, in order to save memory, we need to process images to optimize the program and improve the efficiency of the program. The following is a way to reset the size of the image according to our own requirements:
1. There are two ways to compress the picture. The first is to compress the size of the picture and regenerate the size of the picture: as follows
/** * Compress the picture 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, , )]; UIGraphicsEndImageContext(); return image; }
Second, the second is to modify the file size of the picture: as follows
/** * Compress the picture to the specified file size * * @param image Target image * @param size Target size (maximum value) * * @return Returned image file */ - (NSData *)compressOriginalImage:(UIImage *)image toMaxDataSizeKBytes:(CGFloat)size{ NSData * data = UIImageJPEGRepresentation(image, 1.0); CGFloat dataKBytes = /1000.0; CGFloat maxQuality = 0.9f; CGFloat lastData = dataKBytes; while (dataKBytes > size && maxQuality > 0.01f) { maxQuality = maxQuality - 0.01f; data = UIImageJPEGRepresentation(image, maxQuality); dataKBytes = / 1000.0; if (lastData == dataKBytes) { break; }else{ lastData = dataKBytes; } } return data; }
These are two ways to compress images.
Summarize
The above are the two methods of image compression and compression of image to a specified size introduced by the editor to you by iOS development. I hope it will be helpful to you. If you have any questions, please leave me a message and the editor will reply to you in time. Thank you very much for your support for my website!