我需要帮助调整UIImage的大小。
例如:我在UICollection视图中显示很多图像,但这些图像的大小为2到4 MB。我需要压缩或调整这些图像的大小。
我发现了这个:How to compress/resize image on iPhone OS SDK before uploading to a server?但我不明白如何实现它。
答案 0 :(得分:17)
不确定是否要调整大小或压缩,或两者兼而有之。
下面是压缩的代码:
通过两个简单的步骤使用JPEG Compression:
1)将UIImage转换为NSData
UIImage *rainyImage =[UImage imageNamed:@"rainy.jpg"];
NSData *imgData= UIImageJPEGRepresentation(rainyImage,0.1 /*compressionQuality*/);
这是有损压缩,图像尺寸减小。
2)转换回UIImage;
UIImage *image=[UIImage imageWithData:imgData];
对于缩放,您可以使用Matteo Gobbi提供的答案。但缩放可能不是最好的选择。您更愿意通过压缩获得实际图像的缩略图,因为缩放可能会使您的图像在视网膜显示设备上看起来很糟糕。
答案 1 :(得分:3)
我写了这个函数来缩放图像:
- (UIImage *)scaleImage:(UIImage *)image toSize:(CGSize)newSize {
CGSize actSize = image.size;
float scale = actSize.width/actSize.height;
if (scale < 1) {
newSize.height = newSize.width/scale;
} else {
newSize.width = newSize.height*scale;
}
UIGraphicsBeginImageContext(newSize);
[image drawInRect:CGRectMake(0, 0, newSize.width, newSize.height)];
UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return newImage;
}
使用很简单,例如:
[self scaleImage:yourUIImage toSize:CGMakeSize(300,300)];
答案 2 :(得分:3)
lowResImage = [UIImage imageWithData:UIImageJPEGRepresentation(highResImage, quality)];
答案 3 :(得分:0)
-(UIImage *) resizeImage:(UIImage *)orginalImage resizeSize:(CGSize)size
{
CGFloat actualHeight = orginalImage.size.height;
CGFloat actualWidth = orginalImage.size.width;
float oldRatio = actualWidth/actualHeight;
float newRatio = size.width/size.height;
if(oldRatio < newRatio)
{
oldRatio = size.height/actualHeight;
actualWidth = oldRatio * actualWidth;
actualHeight = size.height;
}
else
{
oldRatio = size.width/actualWidth;
actualHeight = oldRatio * actualHeight;
actualWidth = size.width;
}
CGRect rect = CGRectMake(0.0,0.0,actualWidth,actualHeight);
UIGraphicsBeginImageContext(rect.size);
[orginalImage drawInRect:rect];
orginalImage = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();
return orginalImage;
}
//this image you can add it to imageview.....