我的这个文章是修改简书的blog,本来想在 [作者:郑莫轩 ] 的blog 下评论,但是代码太多了,只能先用一个blog 记录下来,供大家参考。
[代码大放送--iOS图片压缩]
(http://www.jianshu.com/p/974a9537d9f7/comments/2623143#comment-2623143)
- (void)viewDidLoad {
[super viewDidLoad];
[self compressedImageFiles:[UIImage imageNamed:@"1.jpg"] imageKB:20 imageBlock:^(UIImage *image) {
}];
}
/**
* 压缩图片
*
* @param image 需要压缩的图片
* @param fImageBytes 希望压缩后的大小(以KB为单位)
*
* @return 压缩后的图片
*/
- (void)compressedImageFiles:(UIImage *)image
imageKB:(CGFloat)fImageKBytes
imageBlock:(void(^)(UIImage *image))block {
__block UIImage *imageCope = image;
CGFloat fImageBytes = fImageKBytes * 1024;//需要压缩的字节Byte
__block NSData *uploadImageData = nil;
uploadImageData = UIImagePNGRepresentation(imageCope);
NSLog(@"图片压前缩成 %fKB",uploadImageData.length/1024.0);
CGSize size = imageCope.size;
CGFloat imageWidth = size.width;
CGFloat imageHeight = size.height;
if (uploadImageData.length > fImageBytes && fImageBytes >0) {
dispatch_async(dispatch_queue_create("CompressedImage", DISPATCH_QUEUE_SERIAL), ^{
/* 宽高的比例 **/
CGFloat ratioOfWH = imageWidth/imageHeight;
/* 压缩率 **/
CGFloat compressionRatio = fImageBytes/uploadImageData.length;
/* 宽度或者高度的压缩率 **/
CGFloat widthOrHeightCompressionRatio = sqrt(compressionRatio);
CGFloat dWidth = imageWidth *widthOrHeightCompressionRatio;
CGFloat dHeight = imageHeight*widthOrHeightCompressionRatio;
if (ratioOfWH >0) { /* 宽 > 高,说明宽度的压缩相对来说更大些 **/
dHeight = dWidth/ratioOfWH;
}else {
dWidth = dHeight*ratioOfWH;
}
imageCope = [self drawWithWithImage:imageCope width:dWidth height:dHeight];
uploadImageData = UIImagePNGRepresentation(imageCope);
NSLog(@"当前的图片已经压缩成 %fKB",uploadImageData.length/1024.0);
//微调
NSInteger compressCount = 0;
/* 控制在 1M 以内**/
while (fabs(uploadImageData.length - fImageBytes) > 1024) {
/* 再次压缩的比例**/
CGFloat nextCompressionRatio = 0.9;
if (uploadImageData.length > fImageBytes) {
dWidth = dWidth*nextCompressionRatio;
dHeight= dHeight*nextCompressionRatio;
}else {
dWidth = dWidth/nextCompressionRatio;
dHeight= dHeight/nextCompressionRatio;
}
imageCope = [self drawWithWithImage:imageCope width:dWidth height:dHeight];
uploadImageData = UIImagePNGRepresentation(imageCope);
/*防止进入死循环**/
compressCount ++;
if (compressCount == 10) {
break;
}
}
NSLog(@"图片已经压缩成 %fKB",uploadImageData.length/1024.0);
imageCope = [[UIImage alloc] initWithData:uploadImageData];
dispatch_sync(dispatch_get_main_queue(), ^{
block(imageCope);
});
});
}
else
{
block(imageCope);
}
}
/* 根据 dWidth dHeight 返回一个新的image**/
- (UIImage *)drawWithWithImage:(UIImage *)imageCope width:(CGFloat)dWidth height:(CGFloat)dHeight{
UIGraphicsBeginImageContext(CGSizeMake(dWidth, dHeight));
[imageCope drawInRect:CGRectMake(0, 0, dWidth, dHeight)];
imageCope = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return imageCope;
}
网友评论