我正在调试一段代码,其中UIImage可能会多次经历UIImageJPEGRepresentation,我认为这必定是一个bug,并且图像质量会变差,但令人惊讶的是,我们无法直观地看到差异。多次将UIImage压缩成JPEG图像数据
所以我做了一个测试,加载一个图像,并尝试让它通过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压缩了两次?
如果您不使用循环值,循环的重点是什么?我很困惑你真的想做什么?对于它的价值为零,但在你的下一步看,你是不是使数据附加?你能解释更多吗? –
嗨我编辑了我的问题,希望它现在更清晰。 – mkto
尝试NSLog(@“%i”,data.length)会很有趣。查看压缩是否达到极限。 – Roecrew