1、图片压缩
+ (UIImage *)compressImage:(UIImage *)image toByte:(NSUInteger)maxLength {
// Compress by quality
CGFloat compression = 1;
NSData *data = UIImageJPEGRepresentation(image, compression);
if (data.length < maxLength) return image;
CGFloat max = 1;
CGFloat min = 0;
for (int i = 0; i < 6; ++i) {
compression = (max + min) / 2;
data = UIImageJPEGRepresentation(image, compression);
if (data.length < maxLength * 0.9) {
min = compression;
}else if (data.length > maxLength) {
max = compression;
}else {
break;
}
}
UIImage *resultImage = [UIImage imageWithData:data];
if (data.length < maxLength) return resultImage;
// Compress by size
NSUInteger lastDataLength = 0;
while (data.length > maxLength && data.length != lastDataLength) {
lastDataLength = data.length;
CGFloat ratio = (CGFloat)maxLength / data.length;
CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)), (NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blank
resultImage = [[self class] scaleImage:resultImage toNewSize:size];
data = UIImageJPEGRepresentation(resultImage, compression);
}
return resultImage;
}
+ (UIImage *)scaleImage:(UIImage *)image toNewSize:(CGSize)size {
UIGraphicsImageRenderer *renderer = [[UIGraphicsImageRenderer alloc]initWithSize:size];
UIImage *result = [renderer imageWithActions:^(UIGraphicsImageRendererContext * _Nonnull rendererContext) {
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
}];
return result;
}
+ (UIImage *)resizeImage:(UIImage *)image maxSize:(CGSize)size {
CGSize imageSize = image.size;
CGFloat scale = image.scale;
// CGFloat screenScale = [UIScreen mainScreen].scale;
float widthScale = 1, heightScale = 1;
if (imageSize.width * scale > size.width) {
widthScale = (imageSize.width * scale) / (size.width);
}
if (imageSize.height * scale > size.width) {
heightScale = (imageSize.height * scale) / (size.width);
}
float outputScale = MAX(widthScale, heightScale);
if (outputScale > 1) {
return [self.class scaleImage:image toNewSize:CGSizeApplyAffineTransform(imageSize, CGAffineTransformMakeScale(scale/outputScale, scale/outputScale))];
} else {
return image;
}
}
网友评论