Image to raw results with weird error

O

OGG

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);
bmp.UnlockBits(data);
return buffer;
}

private Bitmap ToBitmap(byte[] raw, int w, int h, PixelFormat
pf)
{
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);
bmp.UnlockBits(data);
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.

Thanks.
 
K

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 http://www.bobpowell.net/lockingbits.htm for more information.

--
HTH,

Kevin Spencer
Microsoft MVP

DSI PrintManager, Miradyne Component Libraries:
http://www.miradyne.net
 

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