将UIImage多次压缩为JPEG图像数据

时间:2014-04-09 05:18:25

标签: ios objective-c image uiimage jpeg

我正在调试一段代码,其中UIImage可能会多次通过UIImageJPEGRepresentation,我认为这肯定是一个错误,图像质量会变差,但令人惊讶的是我们无法直观地看到它们之间的区别。 / p>

所以我做了一个测试,加载一个图像,并尝试让它通过UIImageJPEGRepresentation 1000次,令人惊讶的是,1或1000次是否真的无法在视觉上对图像质量产生影响,为什么会如此?

这是测试代码:

        UIImage *image = [UIImage imageNamed:@"photo.jpeg"];

        // Create a data reference here for the for loop later
        // First JPEG compression here
        // I would imagine the data here already has low image quality
        NSData *data = UIImageJPEGRepresentation(image, 0);

        for(int i=0; i<1000; i++)
        {
            // Convert the data with low image quality to UIImage
            UIImage *image = [UIImage imageWithData:data];

            // Compress the image into a low quality data again
            // at this point i would imagine the image get even more low quality, like u resaved a jpeg twice in phootshop
            data = UIImageJPEGRepresentation(image, 0);
        }

        // up to this point I would imagine the "data" has gone through JPEG compression 1000 times
        // like you resave a jpeg as a jpeg in photoshop 1000 times, it should look like a piece of crap
        UIImage *imageFinal = [UIImage imageWithData:data];
        UIImageView *view = [[UIImageView alloc] initWithImage:imageFinal];
        [self.view addSubview:view];

        // but it didn't, the final image looks like it has only gone through the jpeg compression once.

编辑:如果你在objectiveC:

中执行此操作,我可以将我的疑问概括为更简单的代码
        UIImage *image1 = an image..
        NSData *data1 = UIImageJPEGRepresentation(image1, 0);
        UIImage *image2 = [UIImage imageWithData:data1];
        NSData *data2 = UIImageJPEGRepresentation(image2, 0);
        UIImage *imageFinal = [UIImage imageWithData:data2];

imageFinal是否经历了两次JPEG压缩?

3 个答案:

答案 0 :(得分:4)

如您所知,JPG压缩通过更改图像以产生更小的文件大小来工作。您没有看到质量逐渐变差的原因是因为您每次都使用相同的压缩设置。

该算法将源图像改变为足以适应压缩配置文件 - 换句话说,再次以50%压缩50%JPG的结果将生成相同的图像,因为图像不需要更改任何图像更多。

您可以在Photoshop中测试 - 以30%质量的JPG保存照片。重新打开刚刚保存的文件,然后转到Save for Web - 在PNG(未压缩/原始)和JPG 30%之间切换 - 没有区别。

希望这有帮助。

答案 1 :(得分:1)

理想情况下,所有类型的压缩都会缩小图像的大小。有两种类型的压缩描述它们如何影响图像:

有损压缩: 有损压缩会通过从中删除一些数据来减小图像的大小。这通常会导致影响图像质量,这意味着它会降低图像质量

无损压缩: 无损压缩通过改变数据的存储方式来减小图像的大小。因此,这种类型的压缩不会改变图像质量。

请查看您正在使用的压缩类型。

答案 2 :(得分:0)

这可以帮助您减小图像尺寸。把自己的数字放在你想要执行循环的次数上;

UIImage *image = [UIImage imageNamed:@"photo.jpeg"];

for(int i=100; i>0; i--)
{
    UIImage *image = [UIImage imageWithData:data];
    NSData *data = UIImageJPEGRepresentation(image, (0.1 * i);
    NSLog(@"%d",data.length);
}
相关问题