UIImageJPEGRepresentation - memory issue issue

In the iPhone application, I need to send jpg by mail with a maximum size of 300Ko (I do not have a maximum size of mail.app, but this is another problem). To do this, I try to reduce the quality until we get an image under 300Ko.

To get a good quality value (compressionLevel) which give me jpg under 300Ko, I did the following loop. It works, but every time the loop is executed, increasing 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 on how I can do this, or why this is happening? thanks

+4
source share
1 answer

At the very least, it makes no sense to select and release the image each time you go through the loop. This should not be a memory leak, but it is optional, so move alloc / init and exit the loop.

In addition, the data returned by UIImageJPEGRepresentation is automatically freed, so it will hang until the current release pool is depleted (when you return to the main event loop). Think about adding:

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

at the top of the cycle, and

 [p drain] 

in the end. This way you will not skip all intermediate memory.

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

+9
source

Source: https://habr.com/ru/post/1307181/


All Articles