压缩UIImage

6

2
如果您提供一些代码,展示您迄今为止尝试过的内容,那将会很有帮助。 - Connor
1
如果你在处理集合视图同时打开许多图片时考虑内存使用,那么你应该专注于调整大小而不是压缩(因为压缩影响持久性存储器,而不是内存使用)。这是我使用的调整大小例程:https://dev59.com/ZGPVa4cB1Zd3GeqP65J-#10491692 - Rob
被接受的答案确实与标题相符,但与问题文本不符... - Daij-Djan
4个回答

21

您不确定是要调整大小、压缩还是两者兼而有之。

以下代码仅用于压缩:

使用JPEG压缩只需两个简单步骤:

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提供的答案。但是缩放可能不是最好的选择。您更喜欢通过压缩获得实际图像的缩略图,因为缩放可能会使您的图像在视网膜显示设备上看起来糟糕。


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)];

3
lowResImage = [UIImage imageWithData:UIImageJPEGRepresentation(highResImage, quality)];

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.....  

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接