标签:
最近碰到一个比较愚蠢的问题,项目中做的拍照或者从相册选择图片上传时,没有经过处理,直接把原图上传了,导致在列表中看的时候,明明是小图片流量却要爆炸了,想想iphone拍出照片大小可都是以M为单位的。所以赶紧做了下压缩处理再上传。为了方便根据不同压缩需求调用,这里采用调用可修改参数的方法的做法,更加灵活一点。调用的方法如下:
//图片伸缩到指定大小 - (UIImage*)imageByScalingAndCroppingForSize:(CGSize)targetSize forImage:(UIImage *)originImage { UIImage *sourceImage = originImage;// 原图 UIImage *newImage = nil;// 新图 // 原图尺寸 CGSize imageSize = sourceImage.size; CGFloat width = imageSize.width; CGFloat height = imageSize.height; CGFloat targetWidth = targetSize.width;// 目标宽度 CGFloat targetHeight = targetSize.height;// 目标高度 // 伸缩参数初始化 CGFloat scaleFactor = 0.0; CGFloat scaledWidth = targetWidth; CGFloat scaledHeight = targetHeight; CGPoint thumbnailPoint = CGPointMake(0.0,0.0); if (CGSizeEqualToSize(imageSize, targetSize) == NO) {// 如果原尺寸与目标尺寸不同才执行 CGFloat widthFactor = targetWidth / width; CGFloat heightFactor = targetHeight / height; if (widthFactor > heightFactor) scaleFactor = widthFactor; // 根据宽度伸缩 else scaleFactor = heightFactor; // 根据高度伸缩 scaledWidth= width * scaleFactor; scaledHeight = height * scaleFactor; // 定位图片的中心点 if (widthFactor > heightFactor) { thumbnailPoint.y = (targetHeight - scaledHeight) * 0.5; } else if (widthFactor < heightFactor) { thumbnailPoint.x = (targetWidth - scaledWidth) * 0.5; } } // 创建基于位图的上下文 UIGraphicsBeginImageContext(targetSize); // 目标尺寸 CGRect thumbnailRect = CGRectZero; thumbnailRect.origin = thumbnailPoint; thumbnailRect.size.width= scaledWidth; thumbnailRect.size.height = scaledHeight; [sourceImage drawInRect:thumbnailRect]; // 新图片 newImage = UIGraphicsGetImageFromCurrentImageContext(); if(newImage == nil) NSLog(@"could not scale image"); // 退出位图上下文 UIGraphicsEndImageContext(); return newImage; }
// 伸缩图片 if ([self imageByScalingAndCroppingForSize:CGSizeMake(100, 100) forImage:theImage]) {// 伸缩成功 theImage = [self imageByScalingAndCroppingForSize:CGSizeMake(100, 100) forImage:theImage]; }
这个方法也可以用来伸缩图片的尺寸,不过我还是用来压缩的,在不追求高清晰度的情况下,使用还是很方便灵活的,希望能帮到大家~
版权所有:http://blog.csdn.net/cloudox_
标签:
原文地址:http://blog.csdn.net/cloudox_/article/details/50948254