views:

12

answers:

0

I want to be able to dynamically generate PNG24 and PNG8 images using WPF. I was able to generate the PNG24 image that I want using the following code (simplified for the example):

var targetBitmap = new RenderTargetBitmap(128, 16, 96, 96, PixelFormats.Pbgra32);
var drawingVisual = new DrawingVisual();

using (DrawingContext context = drawingVisual.RenderOpen()) {
    var image = new BitmapImage(new Uri("C:\\image.png"));
    context.DrawImage(image, new Rect(0, 0, 22, 22));
}

targetBitmap.Render(drawingVisual);

var bitmap = new FormatConvertedBitmap(renderTargetBitmap, PixelFormats.Pbgra32, BitmapPalettes.Halftone256Transparent, 0.5);

var pngBitmapEncoder = new PngBitmapEncoder();
pngBitmapEncoder.Frames.Add(BitmapFrame.Create(bitmap));

using (Stream fileStream = File.Open("C:\\processed.png", FileMode.Create))
{
    pngBitmapEncoder.Save(fileStream);
}

I couldn't, however, tweak the parameters so that it outputs a PNG8 (palette) image with an arbitrary matte color (say, black). Any clues? Am I on the correct path?

Also, is there some library that can simplify the process? The above snippet looks rather complex for my taste.