newbie: Bitmap.CopyPixels with B/W images
-
Hi all, I'm new to WPF and I'm experimenting with 3.0 bitmaps: I've created a dummy sample code which should: 1) load a bitmap file from disk. It's supposed to be a very small bitmap (e.g. 32x32, 200x100, etc), usually B/W. 2) convert the bitmap to B/W (if required) and get an array representing the black/white pixels. For testing, I "dump" these pixels into a textbox with a fixed-pitch font (e.g. Courier New), by outputting a line for each bitmap row, where '.' represents the 'background' pixel (e.g. white) and '#' the foreground pixel (e.g. black). This way the textbox should give a sketch of the picture. This seems to work fine for non B/W bitmaps, and I can get the 'picture'; but as soon as I convert the loaded bitmap to B/W the textbox shows no more the 'picture', but this seems to be shrunken to occupy just a narrow leftmost portion of the dumped area. Also, I get a set of various values from CopyPixels in a B/W image, while I'd expect just 2, representing black and white. What am I doing wrong here? Here's a sample:
// load a bitmap eventually converting to B/W private BitmapSource LoadBitmap(string sFile, bool bConvertToBW) { BitmapImage bmp = new BitmapImage(new Uri(sFile)); if (bConvertToBW) return new FormatConvertedBitmap(bmp, PixelFormats.BlackWhite, BitmapPalettes.BlackAndWhite, 0); return bmp; } // Handler for Load... button: private void OnLoad(object sender, RoutedEventArgs e) { OpenFileDialog dlg = new OpenFileDialog(); dlg.Filter = "Bitmap Files (*.bmp)|*.bmp"; if (dlg.ShowDialog() != true) return; // load (and convert to BW if required) // IF I PASS true I GET THE ISSUE DESCRIBED ABOVE. WITH false THE DUMP SEEMS TO WORK BitmapSource bs = LoadBitmap(dlg.FileName, true); int nBytesPerPixel = (bs.Format.BitsPerPixel + 7) / 8; int nStride = bs.PixelWidth * nBytesPerPixel; byte[] aPixels = new byte[bs.PixelHeight * nStride]; bs.CopyPixels(aPixels, nStride, 0); // quick and dirty dump pixels to text (BACKGROUND is just a constant I manually set to 0, 255 etc // according to the image I'm testing with, and represents the background color) StringBuilder sb = new StringBuilder(); int nRow; for (int y = 0; y < bs.PixelHeight; y++) { if (y > 0) sb.AppendLine(""); nRow = y * nStride; for (int x = 0; x < bs.PixelWidth; x++) sb.Append(aPixels[nRow + x * nBytesPerPixel] == BACKGROUND ? '.' : '#'); } _txtOut.Text = sb.ToString(); }
Thanks!