mkt*_*kto 5 jpeg image objective-c uiimage ios
我正在调试一段代码,其中 UIImage 可能会通过 UIImageJPEGRepresentation 多次,我认为这一定是一个错误并且图像质量会变差,但令人惊讶的是我们无法在视觉上看到差异。
所以我做了一个测试,加载一张图片,并尝试让它通过 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.
Run Code Online (Sandbox Code Playgroud)
编辑:我的疑问可以总结为一个更简单的代码,如果你在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];
Run Code Online (Sandbox Code Playgroud)
imageFinal 是否经过两次 JPEG 压缩?
如您所知,JPG 压缩的工作原理是更改图像以生成更小的文件大小。您没有看到质量逐渐变差的原因是因为您每次都使用相同的压缩设置。
该算法对源图像的更改刚好足以适合压缩配置文件 - 换句话说,将 50% JPG 的结果再次压缩到 50% 将生成相同的图像,因为图像不需要再进行更改。
您可以在 Photoshop 中对此进行测试 - 以 30% 质量的 JPG 格式保存照片。重新打开刚刚保存的文件,然后转到“另存为 Web” - 在 PNG(未压缩/原始)和 JPG 30% 之间切换 - 不会有任何区别。
希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
2284 次 |
| 最近记录: |