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

Started by
1 comment, last by benryves 13 years, 3 months ago
Hello.

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

string[] col = new string[1000];
col[0]="33,44,255";
col[1]="93,79,167";
col[2]="255,144,6";

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


using C#.net 2005, or newer.

thanks.
Advertisement
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();
}).ToArray();

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

//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);
}

bitmap.Save(path);


Say if there's any part you don't understand.
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.

[Website] [+++ Divide By Cucumber Error. Please Reinstall Universe And Reboot +++]

This topic is closed to new replies.

Advertisement