public static ushort[,] GetPixelArray(Bitmap b, GetPixelMode mode) { bool stretch = mode != GetPixelMode.Raw8Bit; uint maxval = 256; if (stretch) { if (mode == GetPixelMode.StretchTo12Bit) maxval = 4096; else if (mode == GetPixelMode.StretchTo16Bit) maxval = ushort.MaxValue; } Random rnd = new Random((int)DateTime.Now.Ticks); ushort[,] rv = new ushort[b.Width, b.Height]; // GDI+ still lies to us - the return format is BGR, NOT RGB. BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); try { int stride = bmData.Stride; System.IntPtr Scan0 = bmData.Scan0; unsafe { byte* p = (byte*)(void*)Scan0; int nOffset = stride - b.Width * 3; for (int y = 0; y < b.Height; ++y) { for (int x = 0; x < b.Width; ++x) { ushort red = p[2]; if (stretch) { uint stretchedVal = Math.Max(0, Math.Min(maxval, (uint)(red * maxval / 256.0 + (2 * (rnd.NextDouble() - 0.5) * maxval / 256.0)))); red = (ushort) stretchedVal; } rv[x, y] = red; p += 3; } p += nOffset; } } } finally { b.UnlockBits(bmData); } return rv; }
public static ushort[,] GetPixelArray(Bitmap b, GetPixelMode mode) { bool stretch = mode != GetPixelMode.Raw8Bit; uint maxval = 256; if (stretch) { if (mode == GetPixelMode.StretchTo12Bit) { maxval = 4096; } else if (mode == GetPixelMode.StretchTo16Bit) { maxval = ushort.MaxValue; } } Random rnd = new Random((int)DateTime.Now.Ticks); ushort[,] rv = new ushort[b.Width, b.Height]; // GDI+ still lies to us - the return format is BGR, NOT RGB. BitmapData bmData = b.LockBits(new Rectangle(0, 0, b.Width, b.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); try { int stride = bmData.Stride; System.IntPtr Scan0 = bmData.Scan0; unsafe { byte *p = (byte *)(void *)Scan0; int nOffset = stride - b.Width * 3; for (int y = 0; y < b.Height; ++y) { for (int x = 0; x < b.Width; ++x) { ushort red = p[2]; if (stretch) { uint stretchedVal = Math.Max(0, Math.Min(maxval, (uint)(red * maxval / 256.0 + (2 * (rnd.NextDouble() - 0.5) * maxval / 256.0)))); red = (ushort)stretchedVal; } rv[x, y] = red; p += 3; } p += nOffset; } } } finally { b.UnlockBits(bmData); } return(rv); }