• Advertisement
Sign in to follow this  

[.net] Save an array of colors in BMP file

This topic is 2596 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

Recommended Posts


I want to save an array like this to a bitmap file:

string[] col = new string[1000];

I may have 10000 bytes or more, please help for source CODE.

using C#.net 2005, or newer.


Share this post

Link to post
Share on other sites
Does the following help? There's no error checking in it but it should at least be a start.

//create a new bitmap, width*height should equal col.Length
System.Drawing.Bitmap bitmap = new System.Drawing.Bitmap(width, height);

//parse each color and return it in argb format
int[] memory = col.Select(str =>
string[] rgb = str.Split(',');
int red = int.Parse(rgb[0]);
int green = int.Parse(rgb[1]);
int blue = int.Parse(rgb[2]);
return System.Drawing.Color.FromArgb(red, green,blue).ToArgb();

//lock the bitmap
System.Drawing.Imaging.BitmapData data = bitmap.LockBits(
new System.Drawing.Rectangle(0,0,bitmap.Width, bitmap.Height),

//write each scanline to the bitmap
for(int scanline=0; scanline < bitmap.Height; ++scanline)
int offset = data.Stride * scanline;

System.Runtime.InteropServices.Marshal.Copy(memory, scanline * bitmap.Width, data.Scan0 + offset, bitmap.Width * 4);


Say if there's any part you don't understand.

Share this post

Link to post
Share on other sites
A few points on the above code:

  • Once you have finished writing to the Bitmap you should Unlock it with bitmap.UnlockBits(data)
  • Similarly, you should Dispose the Bitmap when you're done. A using statement may help.
  • It produces a PNG, whereas the original poster asked for a BMP. Use bitmap.Save(path, ImageFormat.Bmp) to save as BMP.

Share this post

Link to post
Share on other sites
Sign in to follow this  

  • Advertisement