2014-04-09 35 views
4

我正在调试一段代码,其中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压缩了两次?

+0

如果您不使用循环值,循环的重点是什么?我很困惑你真的想做什么?对于它的价值为零,但在你的下一步看,你是不是使数据附加?你能解释更多吗? –

+0

嗨我编辑了我的问题,希望它现在更清晰。 – mkto

+0

尝试NSLog(@“%i”,data.length)会很有趣。查看压缩是否达到极限。 – Roecrew

回答

2

如您所知,JPG压缩通过改变图像以产生更小的文件大小而起作用。您看不到逐渐恶化的质量是因为您每次都使用相同的压缩设置。

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

你可以在Photoshop中测试这个 - 保存照片出30%质量的JPG。重新打开刚刚保存的文件,然后转到Save for Web - 在PNG(未压缩/原始)和JPG 30%之间翻转 - 不会有任何区别。

希望这会有所帮助。

+1

哦,我不知道。感谢您的澄清:) – mkto

+0

“扩大这个让我们压缩这句话。” this = 1,en = 2。句子现在是“扩展为1让压缩1 s2t2ce”。你无法继续压缩,因为没有东西需要压缩!这同样适用于图像压缩。 – Roecrew

1

所有类型的压缩将理想地减少图像的大小。有两种类型的压缩描述了它们如何影响图像:

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

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

请检查您使用的压缩类型。

+0

我们知道这一点,这并没有回答这个问题。 – Roecrew

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); 
} 
+0

我觉得我的循环例子让很多人困惑不已。我真的只是想了解如果多次调用UIImageJPEGRepresentation多次压缩图像。我不需要for循环来压缩图像。 – mkto

+0

是的,但你可以实现这个代码来检查。我检查了每次这减少NSLog中的NSData大小,试试吧。 –

+0

它是为你工作还是我必须做更多的努力..? –