Search code examples
swiftxcodeimage-processinguigraphicscontext

Image processing with overflowing cache


RESOLVED

I have to process 100 images 2400x2000 px. I do it in cycle in background thread. But on 60th - 70th image the result of rendering is a black or white image ... and message to log:

"Application(2227,0x16c0db000) malloc: can't allocate region *** mach_vm_map(size=15777792) failed (error code=3)"

Example of bad image generation after overflow?

Here is what i do in cycle

        UIGraphicsBeginImageContextWithOptions(PageSize.PX.size, true, 1)

        let context = UIGraphicsGetCurrentContext()

        UIColor.white.setFill()

        context?.fill(CGRect(x: 0, y: 0, width: PageSize.PX.size.width, height: PageSize.PX.size.height))

        image?.draw(in: newImageRect)

        let newImage = UIGraphicsGetImageFromCurrentImageContext()

        UIGraphicsEndImageContext()

At the same time if I process 50 images - everything works fine. Also every loop is added to autorelease pool.

I have already tried UIGraphicsImageRenderer. It is working slower than via image context and after 50th - 60th image they have 0x0 px size....

How can i workaround that? Can i clean image cache somehow? Or maybe i can increase image processing cache? Or....???


Solution

  • Spend 5 days 2-3 hours each for debug. I hope this post will help you if you meet such problem.

    This is very strange situation, and this bug occurs only in beta iOS 12. In iOS 11 all works fine.

    Whats the case ? In my app i need to redraw 100 images from gallery and when i call UIImageJPEGRepresentation in pair with UIGraphicsBeginImageContextWithOptions i think some image processor cache is overflowing (on 50th-60th image - result is 0x0 size or black image. It depends of technology i use). Also pay attention that i added autorelesePool {} in every loop, and my memory consumption is not greater than 200 Mb while images are processing... Also I have tried to debug with instruments and i haven't found any leaks etc.

    I figured it out with running every image operations chain async with 0.1 second delay. I think its not a good approach but on 100 images its increase time of processing from 25 seconds to 35. And it is works fine.

    I hope that in stable iOS 12 it would not be happening.

    Happy coding guys.