IOS compressed image size
Recently, I encountered a silly problem. When I took a picture in a project or selected an image from the album, I did not process it and directly uploaded the source image. As a result, when I looked at it in the list, the traffic for small pictures is exploding. Think about the size of pictures taken by the iphone, which is measured in MB. Therefore, we need to compress the file and upload it again. To facilitate calling based on different compression requirements, we use the method that can modify parameters to make it more flexible. The call method is as follows:
// Scale the image to the specified size-(UIImage *) imageByScalingAndCroppingForSize :( CGSize) targetSize forImage :( UIImage *) originImage {UIImage * sourceImage = originImage; // the original image UIImage * newImage = nil; // new image // original image size CGSize imageSize = sourceImage. size; CGFloat width = imageSize. width; CGFloat height = imageSize. height; CGFloat targetWidth = targetSize. width; // target width CGFloat targetHeight = targetSize. height; // target height // The Scaling Parameter initializes CGFloat scaleFactor = 0.0; CGFloat scaledWidth = targetWidth; CGFloat scaledHeight = targetHeight; CGPoint thumbnailPoint = CGPointMake (0.0, 0.0 ); if (CGSizeEqualToSize (imageSize, targetSize) = NO) {// if the original size is different from the target size, run CGFloat widthFactor = targetWidth/width; CGFloat heightFactor = targetHeight/height; if (widthFactor> heightFactor) scaleFactor = widthFactor; // scale the else scaleFactor = heightFactor according to the width; // scale the scaledWidth = width * scaleFactor; scaledHeight = height * scaleFactor; // locate the image center if (widthFactor> heightFactor) {thumbnailPoint. y = (targetHeight-scaledHeight) * 0.5;} else if (widthFactor I have made it clear in the annotations. This method accepts two parameters: one is the size to be compressed, and the other is the source image. The call process is also very simple, for example:
// Scaling image if ([self SCALING: CGSizeMake (100,100) forImage: theImage]) {// scaling successful theImage = [self imageByScalingAndCroppingForSize: CGSizeMake (100,100) forImage: theImage];}
In this way, I can compress the image file named theImage to a size of 100*100. After testing, after 1 MB of image processing, it would only be over 20 kb, in this way, the traffic pressure is greatly reduced.
This method can also be used to scale the image size, but I still use it for compression. It is very convenient and flexible to use without high definition. I hope it can help you ~