Issue 1210 fix toBitmap handling of stride

git-svn-id: https://zxing.googlecode.com/svn/trunk@2225 59b500cc-1b3d-0410-9834-0bbf25fbcc57
This commit is contained in:
srowen 2012-03-13 16:07:41 +00:00
parent 64b3f0ee79
commit bb809c736e

View file

@ -137,38 +137,40 @@ namespace com.google.zxing.common
/// <returns>A black and white bitmap converted from this ByteMatrix.</returns>
public Bitmap ToBitmap()
{
const byte BLACK = 0;
const byte WHITE = 255;
int width = Width;
int height = Height;
const byte BLACK = 0;
const byte WHITE = 255;
sbyte[][] array = this.Array;
int width = this.Width;
int height = this.Height;
//Here create the Bitmap to the known height, width and format
Bitmap bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
//Create a BitmapData and Lock all pixels to be written
BitmapData bmpData =
bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height),
ImageLockMode.WriteOnly, bmp.PixelFormat);
// create the bitmap and lock the bits because we need the stride
// which is the width of the image and possible padding bytes
var bmp = new Bitmap(width, height, PixelFormat.Format8bppIndexed);
var bmpData = bmp.LockBits(new Rectangle(0, 0, bmp.Width, bmp.Height), ImageLockMode.WriteOnly, bmp.PixelFormat);
try
{
var pixels = new byte[bmpData.Stride*height];
// If you wanted to support formats other than 8bpp, you should use Bitmap.GetPixelFormatSize(bmp.PixelFormat) to adjust the array size
byte[] pixels = new byte[bmpData.Stride * height];
for (int y = 0; y < height; y++)
{
var offset = y*bmpData.Stride;
for (var x = 0; x < width; x++)
{
pixels[offset + x] = this[x, y] ? BLACK : WHITE;
}
}
int iPixelsCounter = 0;
for (int y = 0; y < height; y++)
{
int offset = y * width;
for (int x = 0; x < width; x++)
{
pixels[iPixelsCounter++] = array[y][x] == BLACK ? BLACK : WHITE;
}
iPixelsCounter += bmpData.Stride - width;
}
//Copy the data from the byte array into BitmapData.Scan0
Marshal.Copy(pixels, 0, bmpData.Scan0, pixels.Length);
}
finally
{
//Unlock the pixels
bmp.UnlockBits(bmpData);
}
//Copy the data from the byte array into BitmapData.Scan0
System.Runtime.InteropServices.Marshal.Copy(pixels, 0, bmpData.Scan0, pixels.Length);
return bmp;
//Unlock the pixels
bmp.UnlockBits(bmpData);
//Return the bitmap
return bmp;
}
}
}