Image to raw results with weird error



Hi guys,

I am trying to do a simple task: convert bitmap to raw and back to
bitmap as fast as possible.
Here are the 2 methods I am using:

private byte[] ToRaw(Bitmap bmp)
BitmapData data = bmp.LockBits(new Rectangle(new Point(0,
0), bmp.Size), ImageLockMode.ReadOnly, bmp.PixelFormat);
byte[] buffer = new byte[data.Height * data.Width * 3];
Marshal.Copy(data.Scan0, buffer, 0, buffer.Length);
return buffer;

private Bitmap ToBitmap(byte[] raw, int w, int h, PixelFormat
Bitmap bmp = new Bitmap(w, h, pf);
BitmapData data = bmp.LockBits(new Rectangle(new Point(0,
0), bmp.Size), ImageLockMode.ReadWrite, pf);
Marshal.Copy(raw, 0, data.Scan0, raw.Length);
return bmp;

It works perfectly to any image with width less than 700 pixels or
more than 799 pixels.
The strangest thing happens to a bitmap with width of 701 to 799. It
simply returns the image a little distorted, and I have no clue why.

BTW, if I use simple bitmap.GetPixel / SetPixel it works, but it takes
a lot of time.

Any idea is appreciated.


Kevin Spencer

The width of a row of pixels is not necessarily the width of the row in
bytes. The actual byte width of the row is stored in the BitmapData.Stride
property. So, you need to use that to read and write the the Bitmap. If you
don't want the (possible) padding in the row, you can use the Stride minus
the Width to get the size of the difference. Then you can use that
difference to write the bytes back to the Bitmap.

See for more information.


Kevin Spencer
Microsoft MVP

DSI PrintManager, Miradyne Component Libraries:

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