1

Working in WPF and trying to create a BitmapSource from scratch. The following code gives an Argument Exception " Value does not fall within the expected range." I can't figure out why. I'm still new to WPF and maybe I'm not using the pixel format correctly?

int width = 12;
int height = 14;
byte[] colorData = new byte[width * height * 4];
for(int i = 0; i < colorData.Length; i++)
{
    colorData[i] = 155;  //create all pixels same shade of gray
}
BitmapSource bitmap = BitmapSource.Create(width, height, 96, 96, PixelFormats.Bgra32, null, colorData, width);

1 Answers1

2

The last argument of the BitmapSource.Create method is the stride, i.e. the number of bytes per "scan line".

In case of a pixel format with four bytes per pixel, it is 4 * width:

var stride = 4 * width;
var bitmap = BitmapSource.Create(
    width, height, 96, 96, PixelFormats.Bgra32, null, colorData, stride);
Clemens
  • 123,504
  • 12
  • 155
  • 268