From bb809c736e2c930de4dd98f74502398e6b967366 Mon Sep 17 00:00:00 2001 From: srowen Date: Tue, 13 Mar 2012 16:07:41 +0000 Subject: [PATCH] Issue 1210 fix toBitmap handling of stride git-svn-id: https://zxing.googlecode.com/svn/trunk@2225 59b500cc-1b3d-0410-9834-0bbf25fbcc57 --- csharp/common/ByteMatrix.cs | 58 +++++++++++++++++++------------------ 1 file changed, 30 insertions(+), 28 deletions(-) diff --git a/csharp/common/ByteMatrix.cs b/csharp/common/ByteMatrix.cs index c240a53c3..94d310e7f 100755 --- a/csharp/common/ByteMatrix.cs +++ b/csharp/common/ByteMatrix.cs @@ -137,38 +137,40 @@ namespace com.google.zxing.common /// A black and white bitmap converted from this ByteMatrix. 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; } } }