Fre*_*edM 4 memory iphone uiimage uiimagejpegrepresentation
在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);
}
Run Code Online (Sandbox Code Playgroud)
关于我怎样才能解决它的原因,或者为什么会这样?谢谢
至少,通过循环在每次旅行中分配和释放图像毫无意义.它不应该泄漏内存,但它是不必要的,所以移动alloc/init并释放出循环.
此外,UIImageJPEGRepresentation返回的数据是自动释放的,因此它会一直存在,直到当前版本池耗尽(当您返回主事件循环时).考虑添加:
NSAutoreleasePool* p = [[NSAutoreleasePool alloc] init];
Run Code Online (Sandbox Code Playgroud)
在循环的顶部,和
[p drain]
Run Code Online (Sandbox Code Playgroud)
在末尾.这样你就不会泄漏所有的中间记忆.
最后,对最佳压缩设置进行线性搜索可能效率很低.改为进行二分查找.