Search code examples
iosswiftimage-processingmemory-managementmemory-leaks

Memory Leak on scaling image in iOS using SWIFT


I have an app that displays images and scales them to certain size. Here is the code for the scaling:

static func scaledImage(originalImage image: UIImage, scaledToSize size: CGSize) -> UIImage {        
    UIGraphicsBeginImageContextWithOptions(size, true, 0.0)
    image.drawInRect(CGRectMake(0, 0, size.width, size.height))
    let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return scaledImage
}

and here is how the call to the function is being made:

for i in 0 ..< images.count{
    if let data = images[i].imageData, let originalImage = UIImage(data: data) {
        previewImage = scaledImage(originalImage: originalImage, scaledToSize: desiredSize)            
    } 
} 

The app was crashing for 50 images When i used instruments to find where the memory was allocated it told me that this line allocates 960 MB: image.drawInRect(CGRectMake(0, 0, size.width, size.height))

and that is quite a lot of memory.

So my question is what is being done wrong here? How to solve that memory leak.

I searched through lots of examples on how to scale images but they were more or less the same. There was no example on memory management and due to the fact that i do not have lots of experience in image processing i have no idea how to approach this problem.

Any help here will be much appreciated. Thanks in advance


Solution

  • You have to autorelease the call to scaledImage.

    autoreleasepool {
      previewImage = scaledImage(originalImage: originalImage, scaledToSize: desiredSize)
    }