Question about creating device-compatible bitmaps in C#

Posted by MusiGenesis on Stack Overflow See other posts from Stack Overflow or by MusiGenesis
Published on 2010-04-05T13:37:01Z Indexed on 2010/04/05 14:23 UTC
Read the original article Hit count: 319

Filed under:
|
|
|

I am storing bitmap-like data in a two-dimensional int array. To convert this array into a GDI-compatible bitmap (for use with BitBlt), I am using this function:

public IntPtr GetGDIBitmap(int[,] data)
{
    int w = data.GetLength(0);
    int h = data.GetLength(1);
    IntPtr ret = IntPtr.Zero;

    using (Bitmap bmp = new Bitmap(w, h))
    {
        for (int x = 0; x < w; x++)
        {
            for (int y = 0; y < h; y++)
            {
                Color color = Color.FromArgb(data[x, y]);
                bmp.SetPixel(x, y, color);
            }
        }
        ret = bmp.GetHbitmap();
    }

    return ret;
}

This works as expected, but the call to bmp.GetHbitmap() has to allocate memory for the returned bitmap.

I'd like to modify this method in two (probably related) ways:

  1. I'd like to remove the intermediate Bitmap from the above code entirely, and go directly from my int[,] array to the device-compatible bitmap (i.e. the IntPtr). I presume this would involve calling CreateCompatibleBitmap, but I don't know how to go from that call to actually manipulating the pixel values.
  2. This should logically follow from the answer to the first, but I'd also like my method to re-use existing GDI bitmap handles (instead of creating a new bitmap each time).

How can I do this?

NOTE: I don't really use Bitmap.SetPixel(), as its performance could best be described as "glacial". The code is just for illustration.

© Stack Overflow or respective owner

Related posts about c#

Related posts about .NET