Help to get a Byte array from Bitmap, GetPixel is too slow

G

Guest

I am trying to get a Byte array out of a Bitmap that already exists. The
bitmap is in Format32bppArgb format. I am using the following code but it is
very slow.
Is there any other way to copy RGB values of a Bitmap into byte array?

b = new byte[ABitmap.Width*ABitmap.Height*3];
for(int y=0;y<ABitmap.Height;y++)
{
for(int x=0;x<ABitmap.Width;x++)
{
acolor=ABitmap.GetPixel(x,y);
b=acolor.R;
b[i+1]=acolor.G;
b[i+2]=acolor.B;
i=i+3;
}
}

I have searched a lot for an alternative solution and LockBits seems to be
the right way to do this but it is not working for some reason. I don't get
the right image.
This is what I am doing with LockBits.

Rectangle bounds= new Rectangle(0, 0, ABitmap.Width, ABitmap.Height);
BitmapData bitmapData = ABitmap.LockBits(bounds, ImageLockMode.ReadWrite,
PixelFormat.Format24bppRgb);
b = new byte[ABitmap.Height * bitmapData.Stride];
Marshal.Copy(bitmapData.Scan0, b, 0, ABitmap.Height * bitmapData.Stride);

I lose some pixels, the image gets stretched.

Is there any easyway to copy the RGB values of a Bitmap into byte array?

Please advise.

Kind Regards
Jim
 
J

Jon Skeet [C# MVP]

Jim byrd said:
I am trying to get a Byte array out of a Bitmap that already exists. The
bitmap is in Format32bppArgb format. I am using the following code but it is
very slow.
Is there any other way to copy RGB values of a Bitmap into byte array?

Have you tried saving it to a MemoryStream using ImageFormat.MemoryBmp?
I don't know much about the format myself, but it sounds useful...
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top