Some of my resulting images are slanted, some are not.
Expected Result: (529x22)
Actual Result: (529x22)
Don\'t mind the differen
This expects the stride to correspond to the width, without padding. There can be padding. The padding would "eat" some of the next line, which will therefore appear to shift left.
Since the padding breaks up the lines, the only real way to deal with it (other than using the same padding everywhere) is copying line by line. You can calculate the starting address of a line with bmpData.Scan0 + y * bmpData.Stride
. Copy starting there, for every y
.
// bytes => not using this because it gives error
Yes, because your array does not have padding. So you were telling it to copy more data than the array held.
This seems to work here:
private Bitmap ByteToImage(int w, int h, byte[] pixels)
{
var bmp = new Bitmap(w, h, PixelFormat.Format16bppRgb565);
byte bpp = 2;
var BoundsRect = new Rectangle(0, 0, bmp.Width, bmp.Height);
BitmapData bmpData = bmp.LockBits(BoundsRect,
ImageLockMode.WriteOnly,
bmp.PixelFormat);
// copy line by line:
for (int y = 0; y < h; y++ )
Marshal.Copy(pixels, y * w * bpp, bmpData.Scan0 + bmpData.Stride * y, w * bpp);
bmp.UnlockBits(bmpData);
return bmp;
}
I use a loop to place each row of data at the right spot. The data do not include the padding, but the target address must do so.
Therefore we need to multiply the data access by the actual width * bytePerPixel
but the target adress by the Stride, i.e. the length of the scanline, padded to the next multiple of four bytes. For width=300
it is stride=300
, for width=301
it is stride=304
..
Moving all pixel data in one step can only work when there is no padding, i.e. when the width is a multiple of 4
.