http://www.silverlightchina.net/html/study/WPF/2012/0520/16076.html
RenderTargetBitmap继承自BitmapSource类型,并且定义有Clear和Render两个重要方法,一个将图片全部设置成黑色透明,另一个将WPF中的Visual对象输出到图像中。

RenderTargetBitmap的构造函数参数都是构建位图图像的常用属性:像素大小、DpiX、DpiY和像素存储格式。对于普通图片存储,使用默认值就可以了。Dpi相关的参数用0(0代表使用默认值,而最终图片的Dpi是不可能为0的,通常默认的是96),像素存储格式用PixelFormats.Default(对应Pbgra32)。
DrawingVisual继承自ContainerVisual类型,它定义了一个非常强大的方法:RrenderOpen,返回一个DrawingContext,后者类似GDI中的Device Context,通过它可以向图形终端输出图形数据。
那么可以使用RenderTargetBitmap和DrawingVisual来做一个简单的为图片添加水印的程序。
效果如下:
原始图像:

程序运行后:

下面程序代码,除了需要WPF中常用命名空间外,还需要读者加入如下命名空间:
//WPF图像类型
using System.IO;
//文件/路径相关操作
首先根据图像路径,读取图像文件,就是创建WPF中的图像的基础类型BitmapSource对象,接着创建RenderTargetBitmap对象,使用BitmapSource中图像的属性。最后像素类型有一个特例,必须使用PixelFormats.Default而不是BitmapSource的Format属性。因为目前RenderTargetBitmap只支持Pbgra32类型。而有时BitmapSource的Format会是Bgr32或者其他像素格式。
代码:
var path = @ "E:\Users\Mgen\Pictures\mgenx.jpg";
//读取图像
BitmapSource bitmap = new BitmapImage( new Uri(path, UriKind.Absolute));
//创建RenderTargetBitmap
var rtbitmap = new RenderTargetBitmap(bitmap.PixelWidth,
bitmap.PixelHeight,
bitmap.DpiX,
bitmap.DpiY,
PixelFormats.Default);
接着需要构建界面元素了,因为RenderTargetBitmap的核心是将Visual输出到图像,那么此时我们就开始构建Visual了。此时使用DrawingVisual,然后通过RenderOpen方法获取DrawingContext,把图像和文字输出上去。
首先创建FormattedText对象来做水印:
var text = new FormattedText( "Mgen!",
System.Globalization.CultureInfo.CurrentCulture,
System.Windows.FlowDirection.LeftToRight,
new Typeface(SystemFonts.MessageFontFamily, FontStyles.Normal, FontWeights.Bold, FontStretches.Normal),
24,
Brushes.White);
接下来使用DrawingVisual和DrawingContext进行绘图,把图像和FormattedText输出:
var drawingVisual = new DrawingVisual();
using (var dc = drawingVisual.RenderOpen())
{
dc.DrawImage(bitmap, new Rect(0, 0, bitmap.Width, bitmap.Height));
dc.DrawRectangle(Brushes.Transparent, new Pen(Brushes.White, 7), new Rect(10, 10, 20 + text.Width, 20 + text.Height));
dc.DrawText(text, new Point(20, 20));
}
OK,完成后,调用RenderTargetBitmap的Render方法就可以了,传入刚才的DrawingVisual对象:
//调用RenderTargetBitmap的Render
rtbitmap.Render(drawingVisual);
最后使用BitmapDecoder把RenderTargetBitmap(也属于BitmapSource)保存至文件就可以了:
var bitmapEncoder = new JpegBitmapEncoder();
//加入第一帧
bitmapEncoder.Frames.Add(BitmapFrame.Create(rtbitmap));
//保存至文件(不会修改源文件,将修改后的图片保存至程序目录下)