UIImageJPEGRepresentation - 内存释放问题 [英] UIImageJPEGRepresentation - memory release issue

查看:247
本文介绍了UIImageJPEGRepresentation - 内存释放问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

On a iPhone app, I need to send a jpg by mail with a maximum size of 300Ko (I don't no the maximum size mail.app can have, but it's another problem). To do that, I'm trying to decrease quality until obtain an image under 300Ko.

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

In order to obtain the good value of the quality (compressionLevel) who give me a jpg under 300Ko, I have made the following loop. It's working, but each time time the loop is executed, the memory increase of the size of the original size of my jpg (700Ko) despite the "[tmpImage release];".

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

关于如何解决这个问题的想法,或者为什么会这样?
谢谢

Any ideas about how can i get it off, or why it happens? thanks

推荐答案

至少,通过循环在每次旅行中分配和释放图像毫无意义。它不应该泄漏内存,但它是不必要的,所以移动alloc / init并释放出循环。

At the very least, there's no point in allocating and releasing the image on every trip through the loop. It shouldn't leak memory, but it's unnecessary, so move the alloc/init and release out of the loop.

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

Also, the data returned by UIImageJPEGRepresentation is auto-released, so it'll hang around until the current release pool drains (when you get back to the main event loop). Consider adding:

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

位于循环顶部,

[p drain] 

结尾。这样你就不会泄漏所有的中间内存。

at the end. That way you'll not be leaking all of the intermediate memory.

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

And finally, doing a linear search for the optimal compression setting is probably pretty inefficient. Do a binary search instead.

这篇关于UIImageJPEGRepresentation - 内存释放问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆