我尝试使用UIImageJPEGRepresentation(img,0)减小图像大小,但内存仍然很高。是否有任何选项可以在不降低图像质量的情况下压缩图像。
答案 0 :(得分:0)
CGFloat c = 0.9f;
int maxFileSize = 250*250; //or what ever dimensions u want
NSData *imageData = UIImageJPEGRepresentation(yourImage, c);
while ([imageData length] > maxFileSize && c > 0.1f)
{
c -= 0.1;
imageData = UIImageJPEGRepresentation(yourImage, c);
}
答案 1 :(得分:0)
用于压缩图像用户此类别
@interface UIImage (ImageCompression)
+(UIImage *)compressImage:(UIImage *)image;
@end
@implementation UIImage (ImageCompression)
+(UIImage *)compressImage:(UIImage *)image{
float actualHeight = image.size.height;
float actualWidth = image.size.width;
float maxHeight = 600.0;
float maxWidth = 800.0;
float imgRatio = actualWidth/actualHeight;
float maxRatio = maxWidth/maxHeight;
float compressionQuality = 0.5;//50 percent compression
if (actualHeight > maxHeight || actualWidth > maxWidth){
if(imgRatio < maxRatio){
//adjust width according to maxHeight
imgRatio = maxHeight / actualHeight;
actualWidth = imgRatio * actualWidth;
actualHeight = maxHeight;
}
else if(imgRatio > maxRatio){
//adjust height according to maxWidth
imgRatio = maxWidth / actualWidth;
actualHeight = imgRatio * actualHeight;
actualWidth = maxWidth;
}
else{
actualHeight = maxHeight;
actualWidth = maxWidth;
}
}
CGRect rect = CGRectMake(0.0, 0.0, actualWidth, actualHeight);
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
UIImage *img = UIGraphicsGetImageFromCurrentImageContext();
NSData *imageData = UIImageJPEGRepresentation(img, compressionQuality);
UIGraphicsEndImageContext();
return [UIImage imageWithData:imageData];
}
@end