C# 使用System.Windows.Media.Imaging合成两个位图

C# 使用System.Windows.Media.Imaging合成两个位图,c#,.net,wpf,image-processing,C#,.net,Wpf,Image Processing,我正在尝试使用System.Windows.Media.Imaging将两个大小和格式相同的位图合成为第三个大小和格式相同的文件。我是在WPF(处理LINQPad中的代码)的上下文之外做这件事的,因为我的目的是将其作为不受支持的System.Drawing的替代方案应用到ASP.net应用程序中 // load the files var layerOne = new BitmapImage(new Uri(layerOneFile, UriKind.Absolute)); var layerT

我正在尝试使用System.Windows.Media.Imaging将两个大小和格式相同的位图合成为第三个大小和格式相同的文件。我是在WPF(处理LINQPad中的代码)的上下文之外做这件事的,因为我的目的是将其作为不受支持的System.Drawing的替代方案应用到ASP.net应用程序中

// load the files
var layerOne = new BitmapImage(new Uri(layerOneFile, UriKind.Absolute));
var layerTwo = new BitmapImage(new Uri(layerTwoFile, UriKind.Absolute));

// create the destination based upon layer one
var composite = new WriteableBitmap(layerOne);

// copy the pixels from layer two on to the destination
int[] pixels = new int[(int)layerTwo.Width * (int)layerTwo.Height];
int stride = (int)(4 * layerTwo.Width);
layerTwo.CopyPixels(pixels, stride, 0);
composite.WritePixels(Int32Rect.Empty, pixels, stride, 0);

// encode the bitmap to the output file
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(composite));
using (var stream = new FileStream(outputFile, FileMode.Create))
{
    encoder.Save(stream);
}
这将创建一个与从layerOne加载的文件相同的文件,我所期望的是layerTwo将覆盖在layerOne上。似乎发生的情况是数据已写入BackBuffer,但从未渲染到位图上。。。想必这是调度员通常会做的事情


我哪里做错了?如何才能回到正轨?

问题在于
WritePixels
的第一个参数,它指示要更新的
WriteableBitmap
区域

您可以执行如下操作,而不是执行
Int32Rect.Empty
,并且应该可以看到写在第一个图像上的第二个图像:

Int32Rect sourceRect = new Int32Rect(0, 0, (int)layerTwo.Width, (int)layerTwo.Height);
composite.WritePixels(sourceRect, pixels, stride, 0);

这似乎是解决办法,还有一些其他问题,但我怀疑我需要做更多的思考。有趣的是,我认为Int32Rect.Empty是整个位图的简写,尽管这似乎只适用于CopyPixels。