Reputation: 454
I'm trying to create a bitmap from separate Red, Green, and blue arrays so I can use this bitmap later to create a frame for an avi file (SharpAVI). I've tried the following code which works:
Bitmap Bmp = new Bitmap(Width, Height);
for (int ii = 0; ii < (Width*Height); ii++)
{
ypos = ii / Width;
xpos = ii % Width;
Bmp.SetPixel(xpos, ypos, Color.FromArgb(dataR[ii], dataG[ii], dataB[ii]));
}
the arrays dataR, dataG, and dataB contain the values (0 to 255) of the colors starting from 0,0 and ending on width,height. However, this code is rather slow. I would prefer to directly produce the bitmap from the data, but I'm not sure how. I've seached around and found something in the direction of:
Bitmap bm_Image = new Bitmap(Width, Height, Stride, PixelFormat.Format24bppRgb, ipPtrRGB);
but I don't fully understand how this works. I've read something about padding the data etc. Does anybody know a method to do this fast?
Upvotes: 1
Views: 1028
Reputation: 833
If you want to work with bitmaps faster, I would suggest using this LockBitmap class, found here: http://www.codeproject.com/Tips/240428/Work-with-bitmap-faster-with-Csharp
The implementation is relatively simple, and you can use the same data structures that you are using at the moment. This is what the LockBitmap
implementation will look like for your code:
Bitmap Bmp = new Bitmap(Width, Height);
LockBitmap lockBitmap = new LockBitmap(Bmp);
lockBitmap.LockBits();
for (int ii = 0; ii < (Width*Height); ii++)
{
ypos = ii / Width;
xpos = ii % Width;
lockBitmap.SetPixel(xpos, ypos, Color.FromArgb(dataR[ii], dataG[ii], dataB[ii]));
}
lockBitmap.UnlockBits();
Bmp.Save(filename)
I've used this class myself for a few projects, and I found it to be much faster than the standard .NET functions. The link above even has a benchmark test you can run to see how much faster it is.
Upvotes: 1