How to set Transparency color for the output of RenderTargetBitmap?

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?


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.


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

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

  • 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.

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

  • 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.

    链接地址: http://www.djcxy.com/p/26876.html

    上一篇: WPF效率更高()可视化/控制到位图

    下一篇: 如何为RenderTargetBitmap的输出设置透明度颜色?