1

I have now been looking for almost an hour and just couldn't find an answer. I am currently working on a program that displays a custom image (using WritableBitmap) either in a gray scale or a colourscale with 256 predetermined colours.

The input for the image will be an array of bytes (which works fine if I set the PixelFormat property to PixelFormats.Gray8), but since I need a custom colour scale too, I would like to create custom scales (one for gray and one or more for colours). I think what I need to use is the PixelFormat.Indexed8 property, but I simply can't find out how to use that and how to create a custom colour palette and the internet was not at all helpful on how to create one.

philkark
  • 2,417
  • 7
  • 38
  • 59

1 Answers1

3

You can create a custom BitmapPalette and apply it to a new WriteableBitmap:

var myPalette = new BitmapPalette(new List<Color> 
{ 
    Colors.Red,
    Colors.Blue,
    Colors.Green,
    // ...
});

var writeableBitmap = new WriteableBitmap(
    width, 
    height, 
    96, 
    96, 
    PixelFormats.Indexed8, // Paletted bitmap with 256 colours
    myPalette);

writeableBitmap.WritePixels(...);
Paolo Moretti
  • 54,162
  • 23
  • 101
  • 92
  • Thank you for the answer. Okay, yes I have seen that at some point, but how do I set the 256 colours with the according 256 indices? I mean Colors.Red is simple but I would need to add for example Color.Fromrgb(100, 100, 100) etc... – philkark Aug 31 '12 at 10:56
  • To get a list of grey colors, use this: `var myPalette = new BitmapPalette(Enumerable.Range(0, 256).Select(c => Color.FromRgb((byte)c, (byte)c, (byte)c)).ToList());` – Anders Gustafsson Aug 31 '12 at 11:17
  • @phil13131 You can add any colour you like to your palette. I'm using basic colours to keep the example simple, but can also create colours by using the specified colour channel values. Each colour in the palette is identified by its index number, which corresponds to its position in the palette array. In this case the colour is determined by an index between 0 and 255 into the palette array. – Paolo Moretti Aug 31 '12 at 11:24
  • Thanks, I actually found out I can also simply use `Color.Fromrgb(...)` instead of `Colors.Red` I will see what works best. @Paolo Thank you for the answer again. I didn't even think the index will (quite obviously though) of course simply be the order in which the colours were added. – philkark Aug 31 '12 at 11:25