在iPhone应用程序上,我需要通过邮件发送jpg,最大尺寸为300Ko(我不是mail.app可以拥有的最大尺寸,但这是另一个问题)。为此,我正在尝试降低质量,直到获得低于300Ko的图像为止。
为了获得在300Ko下给我jpg的质量(compressionLevel)的良好值(value),我进行了以下循环。
它正在工作,但是每次执行循环时,尽管“[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);
}
关于如何实现它或为什么它会发生的任何想法?
谢谢
最佳答案
至少,在每次循环中分配和释放镜像都是没有意义的。它不应该泄漏内存,但这是不必要的,因此将alloc/init移出循环。
而且,由UIImageJPEGRepresentation返回的数据将自动释放,因此它将一直徘徊直到当前释放池耗尽(当您回到主事件循环时)。考虑添加:
NSAutoreleasePool* p = [[NSAutoreleasePool alloc] init];
在循环的顶部,并且
[p drain]
在最后。这样,您就不会泄漏所有中间存储器。
最后,对最佳压缩设置进行线性搜索可能效率很低。而是执行二进制搜索。
关于iphone - UIImageJPEGRepresentation-内存释放问题,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/2655769/