I am trying to use System.Windows.Media.Imaging to composite two bitmaps of the same size and format into a third file of the same size and format. I am doing this outside of the context of WPF (working on the code in LINQPad) as the intention is to work this into a ASP.net application as an alternative to the unsupported System.Drawing.
// 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);
}
This creates a file that is identical to the file loaded from layerOne, what I was expecting was layerTwo to be overlayed on layerOne. What appears to be happening is the data is been written to the BackBuffer but is never being rendered onto the bitmap… presumably this is something the dispatcher would normally be doing.
Where am I going wrong? and how can I get back on track?
The problem is with the first argument for
WritePixels, which indicates the area of theWriteableBitmapto update.Instead of
Int32Rect.Empty, you can do something like the following and should see the second image written over the first: