Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to set Transparency color for the output of RenderTargetBitmap?

Tags:

wpf

I'm trying to save a Visual object, which has a transparent background, to 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;
    }

It works, but the transparent pixels are rendered with black color. What the simplest way to change these transparent pixels to another color?

like image 501
Néstor Sánchez A. Avatar asked Mar 28 '11 20:03

Néstor Sánchez A.


2 Answers

If you are saving the image as a JPG, transparent will appear black since JPG does not support transparent channel AFAIK. Possible solution: save as a PNG, or paint with a reasonable background color.

like image 121
Felice Pollano Avatar answered Nov 04 '22 04:11

Felice Pollano


I haven't tested this, but in theory it should work.

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

  2. Then query the Alpha channel of all those pixels and where they are equal to 0x00 (fully transparent), set the color to whatever you'd like in the background. If you want to be more elegant, you'd have to do the "color math" to properly set the colors in semi-transparent pixels.

  3. Finally, after you have an adjusted array of pixels, create a new BitmapSource from them.

  4. To save that to disk, you'll probably have to create an Image in memory and set its Source to your new Bitmapsource and run your RenderToBitmap again.

Hope it helps.

EDIT: After posting this, I had another thought that may be easier.

If you take a clone or snapshot of the visual element you're trying to save and put it into a new in-memory panel (such as a grid or a canvas), you could simply change the background of the panel to be the color you want.

Then you'd use the panel as your source for RenderTargetBitmap.

like image 40
SergioL Avatar answered Nov 04 '22 06:11

SergioL