views:

105

answers:

4

I'm building a System.Drawing.Bitmap in code from a byte array, and i'm not sure what properties and such need to be set so that it will properly save as a .BMP file. I have Bitmap b = new Bitmap(width, height, PixelFormat.Format32bppArgb); as my constructor and

    for (int i = 1; i < data.Length; i += 2;)
    {
        Color c = new Color();
        c.A = data[i];
        c.R = data[i];
        c.G = data[i];
        c.B = data[i];
        int x = (i + 1) / 2;
        int y = x / width;
        x %= width;
        b.SetPixel(x, y, c);
    }

as the code that sets the bitmap data (it's reading from a byte array containing 16 bit little'endian values and converting them to grayscale pixels). What else should be done to make this bitmap saveable?

A: 

(starting at i=1 looks like a bad move, btw - should be 0?)

What happens when you try to save it (b.Save("foo.bmp");)?

Also; if this is a large image, you may want to look at LockBits; a related post is here (although it uses a rectangular array, not a 1-dimensional array).

Marc Gravell
I was advised to throw out the upper byte of each 16 bit value when converting to a Color, so that's why i start at 1 and add 2. I haven't quite gotten to the point at which i can test but i'm working on it.
RCIX
+1  A: 

Nothing else needs to be done, you can save the bitmap right after setting it's image data.

Also note that the SetPixel method used in a loop is utterly slow, see this link for more information.

arul
I'm going for working code rather than speed at the moment. This does look like the best answer though, thanks!
RCIX
+1  A: 

An instance of the Bitmap class can be saved as a .bmp file just by calling the Save(string filename) method.

As mentioned in other answers, setting the pixels one at a time in a loop is a bit slow.

Also, you can't set the properties of a Color struct, you will need to create it as follows:

Color c = Color.FromArgb(data[i], data[i + 1], data[i + 2], data[i + 3]);

(Not sure what is in your data[] array)

Bing
i've since worked out an alternate method for converting my data to int values, thanks anyway!
RCIX
A: 

Your formula for calculating grayscale is normally not the one used. Granted, it will work pretty well but you most likely want to keep to the standard. The eye is more receptive to some colors (green) so you usually use another weighing. I would set the color like this;

c.R = 0.3 * data[i];
c.G = 0.59 * data[i];
c.B = 0.11 * data[i];
c.A = 1;

See Wikipedia article on Grayscale for more information

kigurai