UIGraphicsGetImageFromCurrentImageContext memory leak for image scaling

My iPhone application downloads image files from the server, saves it to NSTemporaryDirectory (), and then loads the image in the user interface asynchronously. The stream code is as follows:

  • Show a view with an indicator of download activity and start the image downloader in the background.
  • As soon as the image is downloaded, it will be written to a file.
  • The timer in the download view continues to check for the presence of the file in the temp directory and, as soon as it is available, loads the image from the file and adds the image to the user interface.
  • Before adding an image, it is scaled to the required size.

The problem is that I am using UIGraphicsGetImageFromCurrentImageContext to scale the image. It seems that the memory used by the image context is not cleared. Application memory simply increases as more files are downloaded.

The following code is below:

Code for image scaling:


-(UIImage*)scaleToSize:(CGSize)size image:(UIImage *)imageref
{
 UIGraphicsBeginImageContext(size);
 [imageref drawInRect:CGRectMake(0, 0, size.width, size.height)];
 UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
 UIGraphicsEndImageContext();
 return scaledImage;
}

Download image from temp directory:


-(void)loadImageFromFile: (NSString *) path
{
 NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];
 UIImage * imm = [[[UIImage alloc] initWithContentsOfFile:path] autorelease];
 [self performSelectorOnMainThread:@selector(insertImage:) withObject:imm waitUntilDone:YES];
 [pool release];
}

Adding an image to view (a subset of the code):


 self.imageContainer = [[UIImageView alloc] initWithFrame:CGRectMake(0,80,320,250)];
 [self addSubview:self.imageContainer];
 self.imageContainer.image = [self scaleToSize:CGSizeMake(320.0f, 250.0f) image:imm];
 [imageContainer release];

What am I missing here?

+3
source share
1 answer

One way to avoid leakage from UIGraphicsGetImageFromCurrentImageContextis to not cause it at all by resizing the container, instead of directly resizing the image:

self.imageContainer.contentMode = UIViewContentModeScaleAspectFit;
self.imageContainer.frame = CGRectMake(self.imageContainer.frame.origin.x, self.imageContainer.frame.origin.y, 320.0f, 250.0f);
0
source

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


All Articles