等比压缩图片的方法
- (UIImage*)imageEqualRatioScaledToSize:(CGSize)targetSize
{
UIImage *sourceImage = self;
UIImage *newImage = nil;
CGSize imageSize = sourceImage.size;
CGFloat srcWidth = imageSize.width;
CGFloat srcHeight = imageSize.height;
CGFloat targetWidth = targetSize.width;
CGFloat targetHeight = targetSize.height;
if (srcWidth <= targetWidth && srcHeight <= targetHeight) {
// 如果源图已经小于缩放尺寸,则返回源图
newImage = sourceImage;
} else {
// 如果源图长或宽大于缩放尺寸,则等比缩放
double scale = (double)targetWidth/srcWidth < (double)targetHeight/srcHeight ? (double)targetWidth/srcWidth : (double)targetHeight/srcHeight;
CGFloat scaleWidth = scale * srcWidth;
CGFloat scaleHeight = scale * srcHeight;
CGSize newSize = CGSizeMake(scaleWidth, scaleHeight);
UIGraphicsBeginImageContext(newSize);
CGRect thumbnailRect = CGRectMake(0, 0, scaleWidth, scaleHeight);
[sourceImage drawInRect:thumbnailRect];
newImage = UIGraphicsGetImageFromCurrentImageContext();
if(newImage == nil)
DLog(@"could not scale image");
UIGraphicsEndImageContext();
}
return newImage;
}