This is my piece of code that i gathered from here.
private unsafe byte[] BmpToBytes_Unsafe(Bitmap bmp)
{
BitmapData bData = bmp.LockBits(new Rectangle(0,0,1000,1000),
ImageLockMode.ReadOnly,
PixelFormat.Format24bppRgb);
// number of bytes in the bitmap
int byteCount = bData.Stride * bmp.Height;
byte[] bmpBytes = new byte[byteCount];
// Copy the locked bytes from memory
Marshal.Copy(bData.Scan0, bmpBytes, 0, byteCount);
Marshal.
// don't forget to unlock the bitmap!!
bmp.UnlockBits(bData);
return bmpBytes;
}
I have a function that gets byte from above mentioned function and just displays it without further processing. But i get the inverted image at the output. Can somebody explain?
When you say “inverted”, I suppose that you mean upside down?
You can’t rely on the “l33t hax0r skillz” of the person posting that code. He lacks some vital information about how bitmaps are handled in memory.
When you read the data from the bitmap you can’t read it all in one chunk. The data is stored in lines, and the lines may be stored either with the top line first or the bottom line first. Also, there may be padding between the lines to get each line on an even word boundary.
The
Scan0property is a pointer to the start of the first line, and theStrideproperty is the offset to the start of the next line. TheWidthproperty can be used to determine how much data there is in each line.So, you have to copy the data one line at a time: