Note that there are some explanatory texts on larger screens.

plurals
  1. POHow do I prevent a memory leak with UIImage.FromImage(context.ToImage())?
    primarykey
    data
    text
    <p>I have the following function to convert a byte array of pixels into an image. However, I have a memory leak in the line:</p> <p>unpackedImage = UIImage.FromImage(context.ToImage());</p> <p>When I comment out the line above, the leak goes away. The leak is so bad that iOS is killing my app within about 30 seconds of startup. It's because of this line of code.</p> <p>How do I prevent this memory leak? Is there a better way to do what I am trying to do?</p> <pre><code> public static void DrawCustomImage2(IntPtr buffer, int width, int height, int bytesPerRow, CGColorSpace colSpace, byte[] rawPixels, ref UIImage unpackedImage) { GCHandle pinnedArray = GCHandle.Alloc(rawPixels, GCHandleType.Pinned); IntPtr pointer = pinnedArray.AddrOfPinnedObject(); // Set a grayscale drawing context using the image buffer CGBitmapContext context = new CGBitmapContext(pointer, width, height, 8, bytesPerRow, colSpace, CGImageAlphaInfo.None); // Turning off interpolation and Antialiasing is supposed to speed things up context.InterpolationQuality = CGInterpolationQuality.None; context.SetAllowsAntialiasing(false); try { unpackedImage = UIImage.FromImage(context.ToImage()); // Convert the drawing context to an image and set it as the unpacked image } finally { pinnedArray.Free(); if (context != null) context.Dispose(); } } </code></pre> <p>Here is the profiling screenshot (checked items all disappear when the critical line of code is commented out). You can see how the checked items (especially the Malloc) grow over time.</p> <p><img src="https://i.stack.imgur.com/riZzf.png" alt="Profiling Screenshot"></p> <p>Here is the zoom-in view on the Malloc 1.50KB. You can see in the Extended Detail pane on the right that it is calling CGBitmapContextCreateImage and CGDataProviderCreateWithCopyOfData and then a malloc. <img src="https://i.stack.imgur.com/e9jcz.png" alt="Malloc 1.50KB Profiling Screenshot"></p> <p>Here is the profiling screenshot with Rolf's suggestion. I ran the image loop twice. You can see that it cleans up the extra memory at the end of the first loop, but the system didn't clean it up fast enough the second time and iOS killed my app (you can see the low memory warning flags in the top right corner). <img src="https://i.stack.imgur.com/XpTTU.png" alt="enter image description here"></p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload