Memory leak with CreateBitmapSourceFromHBitmap

时间:2019-02-24 03:09:24

标签: c# wpf winforms bitmap data-conversion

I've played with OpenCL.Net and found some example to work with images. I'm still not sure how everything work yet, but it looked OK till I added a slider to be able to change a parameter and realized that I have huge memory leak. I didn't know were it was but I just started to change code for setting output bitmap as it was creating new bitmap for each filter pass and in process I was surprised that old method was actually the whole cause of the problem, even though I'm still creating new BitmapSource for each pass.

This was the old method:

private BitmapSource covertToBitmapSource2() {
    //Get a pointer to our unmanaged output byte[] array
    GCHandle pinOutArr = GCHandle.Alloc(outBytes, GCHandleType.Pinned);
    IntPtr outputBmpPointer = pinOutArr.AddrOfPinnedObject();
    //Create a new bitmap with processed data and save it to a file.
    Bitmap outputBitmap = new Bitmap(bd.Width, bd.Height,
          bd.Stride, PixelFormat.Format32bppArgb, outputBmpPointer);

    var b = System.Windows.Interop.Imaging.CreateBitmapSourceFromHBitmap(
      outputBitmap.GetHbitmap(),
      IntPtr.Zero,
      Int32Rect.Empty,
      BitmapSizeOptions.FromEmptyOptions());

    pinOutArr.Free();
    return b;
}

From what I understand this creates unmanaged pointer to the managed array in order to create unmanaged Bitmap just to convert it back to managed BitmapSource ? But even if it's not weird and I just don't understand it, can someone explain why is this leaking?

I've replaced this with following code:

private BitmapSource covertToBitmapSource() {
    WriteableBitmap w = new WriteableBitmap(bd.Width, bd.Height,
        96, 96, System.Windows.Media.PixelFormats.Pbgra32,
        null);
    w.WritePixels(new Int32Rect(0,0,bd.Width, bd.Height),
        outBytes, bd.Stride, 0);
    return w;
}

Everything else stays the same and the problem is gone.

Also, I can't figure out why the output image looks exactly the same even if the first method uses ARGB format and second BGRA? I didn't found ARGB in Media.PixelFormats and expected the colors to be wrong but they look correct.

0 个答案:

没有答案