I am trying to dynamically create a Bitmap Image using byte array using following code
Bitmap GetImage()
{
IntPtr ip = Marshal.AllocCoTaskMem(imagesize);
//some code to fill ip
Image img = new Bitmap(
w,
h,
-stride,
PixelFormat.Format24bppRgb,
(IntPtr)(ip.ToInt32() + imagesize - stride)
);
Marshal.FreeCoTaskMem( ip); // Comment this line to work
return img;
}
void SaveImage()
{
Image img = GetImage();
img.save("test.bmp"); // This call fails
img.Dispose();
}
Now my problem is I want to return a Bitmap but at the same time I don't want to keep the ip pointer as that memory allocated leaks. It is never freed. How can I return a Image created with bytes array and without bothering the caller of the function GetImage() to free up the memory.