cdts/xdts-ios 3/TreeHole/Code/Gategory/UIImageEx/UIImage+Scale.m

103 lines
3.7 KiB
Mathematica
Raw Normal View History

2023-07-27 09:20:00 +08:00
//
// UIImage+Scale.m
// Meet
//
// Created by yuqingyuan on 2018/9/28.
// Copyright © 2018 ko1o. All rights reserved.
//
#import "UIImage+Scale.h"
@implementation UIImage (Scale)
+ (UIImage *)imageWithImage:(UIImage *)image scaledToSize:(CGSize)size
{
if ([[UIScreen mainScreen] respondsToSelector:@selector(scale)]) {
UIGraphicsBeginImageContextWithOptions(size, NO, [[UIScreen mainScreen] scale]);
} else {
UIGraphicsBeginImageContext(size);
}
[image drawInRect:CGRectMake(0, 0, size.width, size.height)];
UIImage *newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
+ (UIImage *)imageWithImage:(UIImage *)image scaledToMaxWidth:(CGFloat)width maxHeight:(CGFloat)height
{
CGSize newSize = [self sizeWithImageSize:image.size scaledToMaxWidth:width maxHeight:height];
return [self imageWithImage:image scaledToSize:newSize];
}
+ (CGSize)sizeWithImageSize:(CGSize)size scaledToMaxWidth:(CGFloat)width maxHeight:(CGFloat)height
{
CGFloat oldWidth = size.width;
CGFloat oldHeight = size.height;
CGFloat scaleFactor = (oldWidth > oldHeight) ? width / oldWidth : height / oldHeight;
CGFloat newHeight = oldHeight * scaleFactor;
CGFloat newWidth = oldWidth * scaleFactor;
CGSize newSize = CGSizeMake(newWidth, newHeight);
return newSize;
}
NSData *comprossImageToSize(UIImage *image, int size) {
int maxLength = size; // 500k
//over
CGFloat compression = 1;
NSData *data = UIImageJPEGRepresentation(image, compression);
if (data.length < maxLength) return UIImageJPEGRepresentation(image, 1.0);
// 60.015625
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;
}
}
//over
UIImage *resultImage = [UIImage imageWithData:data];
if (data.length < maxLength) return data;
//
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)));
//
UIGraphicsBeginImageContext(size);
[resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];
resultImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
//
data = UIImageJPEGRepresentation(resultImage, compression);
}
return data;
}
NSData *compressImageToDataIfNeed(UIImage *image)
{
return comprossImageToSize(image, 500 * 1000);
}
UIImage *compressImageToSizeIfNeed(UIImage *image, int size)
{
NSData *data = comprossImageToSize(image, size);
return [[UIImage alloc] initWithData:data];
}
@end