inutan
inutan

Reputation: 10888

Marshal - Do I need to free any resources?

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.

Upvotes: 6

Views: 385

Answers (3)

MarcinJuraszek
MarcinJuraszek

Reputation: 125630

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)
{
   //...
}

Upvotes: 1

Hans Passant
Hans Passant

Reputation: 941715

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.

Upvotes: 4

Trifon
Trifon

Reputation: 1151

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.

Upvotes: 2

Related Questions