How to set transparency color for RenderTargetBitmap output?

I am trying to save a visual object with a transparent background into a bitmap using RenderTargetBitmap ...

public static RenderTargetBitmap RenderToBitmap(this Visual Source, int Width, int Height) { var Result = new RenderTargetBitmap(Width, Height, 96, 96, PixelFormats.Default); Result.Render(Source); return Result; } 

This works, but transparent pixels are displayed in black. What is the easiest way to change these transparent pixels to a different color?

+8
wpf
source share
2 answers

If you save the image in JPG format, the transparency will be black because JPG does not support the AFAIK transparent channel. Possible solution: save as PNG or draw with a reasonable background color.

+1
source share

I have not tested this, but theoretically it should work.

  • Use the CopyPixels () method to extract all the pixel data from your RenderTargetBitmap into an array.

  • Then request the alpha channel of all these pixels and where they are 0x00 (fully transparent), set the color to any place in the background. If you want to be more elegant, you will need to do “color math” in order to correctly set the colors in translucent pixels.

  • Finally, after you have configured the pixel array, create a new BitmapSource from them.

  • To save this to disk, you probably have to create an image in memory and set its source to a new bitmap resource and run RenderToBitmap again.

Hope this helps.

EDIT: After posting this, another thought that might be simpler.

If you take a clone or snapshot of a visual element that you are trying to save and place it in a new memory panel (for example, a grid or canvas), you can simply change the background of the panel to be the color you want.

You will then use the panel as your source for the RenderTargetBitmap.

+1
source share

All Articles