Sign in to follow this  

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

This topic is 2522 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

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.

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.

[code]//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);
[/code]

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:

[list]
[*]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 [url=http://msdn.microsoft.com/en-us/library/yh598w02.aspx]using[/url] 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.
[/list]

Share this post


Link to post
Share on other sites

This topic is 2522 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.

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this