Search code examples
swiftuikituigraphicscontext

Adding border to UIImages memory issue


I'm trying to add a border to my images by drawing it in a context but the memory keeps growing.

func borderImages(image: [UIImage]) -> [UIImage] {
    let width: CGFloat = 3000
    let height: CGFloat = 3000
    var borderedImages = [UIImage]()

    for image in images {
        autoreleasepool {
            UIGraphicsBeginImageContextWithOptions(CGSize(width: width, height: height), true, 1.0)

            let x: CGFloat = (width - image.size.width)/2.0
            let y: CGFloat = (height - image.size.height)/2.0

            let rect = CGRect(x: x, y: y, width: image.size.width, height: image.size.height)
            image.draw(in: rect)

            if let borderedImage = UIGraphicsGetImageFromCurrentImageContext() {
                borderedImages.append(borderedImage)

            }
            UIGraphicsEndImageContext()
        }
    }

    return borderedImages
}

I tried adding autoreleasepool as suggested from here. Doesn't seem to make any difference. This is what allocations look like before it crashes.enter image description here Any suggestions on how I can fix this? Am I using autoreleasepool wrong?


Solution

  • So after discussing it and checking out the images it looks like trying to process 100 at once it just too much for the memory handling of an iOS device.

    The solution is going to be to batch the files for processing something like this:

    1. Create next batch.
    2. Process/upload images in the current batch.
    3. Dispose of the current batch.
    4. Repeat from 1 above.

    Doing that you should never have to hold too many in memory at once.