Question

I am using below method to convert byte[] to Bitmap:

    public static Bitmap ByteArrayToBitmap(byte[] byteArray)
    {
        int width = 2144;
        int height = 3;
        Bitmap bitmapImage = new Bitmap(width, height, PixelFormat.Format32bppPArgb);
        BitmapData bmpData = bitmapImage.LockBits(new Rectangle(0, 0, width, height), ImageLockMode.ReadWrite, PixelFormat.Format32bppPArgb);
        IntPtr ptr = bmpData.Scan0;

        try
        {
            Marshal.Copy(byteArray, 0, ptr, byteArray.Length);
            bitmapImage.UnlockBits(bmpData);
            return bitmapImage;
        }
        finally
        {
           //Marshal.FreeHGlobal(ptr); //Do I need this?
        }
    }

Just wondering if I need to free up any resources here? Tried calling Marshal.FreeHGlobal(ptr), but I am getting this error:

Invalid access to memory location.

Can anyone please guide?

Also, FYI, I could use MemoryStream to get Bitmap out of byte[], but I was getting 'Parameter not valid' exception in that case. That's why took the route to Marshal.

Was it helpful?

Solution 3

The only thing you should do is be sure you call dispose on the returned Bitmap. The best way to do that is placing it within using block.

using(Bitmap myBitmap = ByteArrayToBitmap(someArray)
{
   //...
}

OTHER TIPS

You only use FreeHGlobal when you used AllocHGlobal. You didn't so don't call it. You did allocate unmanaged memory, it was done by new Bitmap. That's released by Dispose() or the GC. Later.

You certainly should use that finally block, that's where you call UnlockBits(). That 'releases' the pointer.

No you do not need to.

The memory that is allocated for the bitmap is allocated by the Bitmap constructor and it will be freed when the bitmapImage gets disposed.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top