本文主要是介绍iOS代码剪裁图片尺寸/压缩图片质量,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
#pragma mark -----改变显示图片的尺寸—————
- (UIImage*) OriginImage:(UIImage*)image scaleToSize:(CGSize)size {UIGraphicsBeginImageContext(size); //size 为CGSize类型,即你所需要的图片尺寸[image drawInRect:CGRectMake(0, 0, size.width, size.height)];UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();return scaledImage; //返回的就是已经改变的图片
}#pragma mark - 连续压缩图片到50K以下NSData *data = [self compressQualityImage:[UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:imageArray[0]]]] andMaxLength:50000];//单位 byte- (NSData *)compressQualityImage:(UIImage *)image andMaxLength:(NSInteger)maxLength {CGFloat compression = 1;NSData *data = UIImageJPEGRepresentation(image, compression);//NSLog(@"Before compressing quality, image size = %ld KB",data.length/1024);if (data.length < maxLength) return data;CGFloat max = 1;CGFloat min = 0;for (int i = 0; i < 6; ++i) {compression = (max + min) / 2;data = UIImageJPEGRepresentation(image, compression);//NSLog(@"Compression = %.1f", compression);//NSLog(@"In compressing quality loop, image size = %ld KB", data.length / 1024);if (data.length < maxLength * 0.9) {min = compression;} else if (data.length > maxLength) {max = compression;} else {break;}}//NSLog(@"After compressing quality, image size = %ld KB", data.length / 1024);if (data.length < maxLength) return data;UIImage *resultImage = [UIImage imageWithData:data];// Compress by sizeNSUInteger lastDataLength = 0;while (data.length > maxLength && data.length != lastDataLength) {lastDataLength = data.length;CGFloat ratio = (CGFloat)maxLength / data.length;//NSLog(@"Ratio = %.1f", ratio);CGSize size = CGSizeMake((NSUInteger)(resultImage.size.width * sqrtf(ratio)),(NSUInteger)(resultImage.size.height * sqrtf(ratio))); // Use NSUInteger to prevent white blankUIGraphicsBeginImageContext(size);[resultImage drawInRect:CGRectMake(0, 0, size.width, size.height)];resultImage = UIGraphicsGetImageFromCurrentImageContext();UIGraphicsEndImageContext();data = UIImageJPEGRepresentation(resultImage, compression);//NSLog(@"In compressing size loop, image size = %ld KB", data.length / 1024);}//NSLog(@"After compressing size loop, image size = %ld KB", data.length / 1024);return data;
}
这篇关于iOS代码剪裁图片尺寸/压缩图片质量的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!