5

在 iPhone 应用程序上,我需要通过邮件发送最大大小为 300Ko 的 jpg(我没有 mail.app 可以具有的最大大小,但这是另一个问题)。为此,我试图降低质量,直到获得低于 300Ko 的图像。

为了获得好值的质量(compressionLevel)谁给我300Ko以下的jpg,我做了如下循环。它正在工作,但是每次执行循环时,尽管有“[tmpImage release];”,但我的 jpg (700Ko) 原始大小的内存会增加。

float compressionLevel = 1.0f;
int size = 300001;
while (size  > 300000) {
    UIImage *tmpImage =[[UIImage alloc] initWithContentsOfFile:[self fullDocumentsPathForTheFile:@"imageToAnalyse.jpg"]];
    size = [UIImageJPEGRepresentation(tmpImage, compressionLevel) length];
    [tmpImage release];
        //In the following line, the 0.001f decrement is choose just in order test the increase of the memory  
    //compressionLevel = compressionLevel - 0.001f;
    NSLog(@"Compression: %f",compressionLevel);
} 

关于如何摆脱它或为什么会发生的任何想法?谢谢

4

1 回答 1

9

至少,在每次循环中分配和释放图像是没有意义的。它不应该泄漏内存,但它是不必要的,所以将 alloc/init 和 release 移出循环。

此外,UIImageJPEGRepresentation 返回的数据是自动释放的,因此它会一直存在,直到当前释放池耗尽(当您返回主事件循环时)。考虑添加:

NSAutoreleasePool* p = [[NSAutoreleasePool alloc] init];

在循环的顶部,并且

[p drain] 

在最后。这样你就不会泄漏所有的中间内存。

最后,对最佳压缩设置进行线性搜索可能效率很低。改为进行二进制搜索。

于 2010-04-16T20:26:17.407 回答