我见过很多合并两个 System.Drawing.Image/Bitmap 对象来创建单个图像的示例,但我正在尝试使用 System.Windows.Controls.Image 对象来完成此操作。
例如,如果我有以下对象:
System.Windows.Controls.Image image1;
System.Windows.Controls.Image image2;
如何将两个图像合并到现有图像对象中?例如:
image1.Merge(image2, new Rect(0, 0, 15, 15);
目标是获得包含两个图像的图像内容的单个图像。
我尝试将它们转换为 System.Drawing.Image 对象,但程序的其他部分要求它们是 System.Windows.Controls.Image 对象。
您可以使用
DrawingVisual
和 RenderTargetBitmap
创建重叠图像,然后只需更改 Image.Source
属性即可。这是一个例子:
public static class ImageExtensions
{
public static void Merge(this Image image1, Image image2, Rect r)
{
// Get sources from each image
BitmapImage source1 = (BitmapImage)image1.Source;
BitmapImage source2 = (BitmapImage)image2.Source;
// Overlap images and save to image 1
image1.Source = OverlapImages(source1, source2, r);
}
private static BitmapSource OverlapImages(BitmapImage image1, BitmapImage image2, Rect r)
{
// Create a DrawingVisual to combine the images
DrawingVisual visual = new DrawingVisual();
using (DrawingContext ctx = visual.RenderOpen())
{
// Draw the first image
ctx.DrawImage(image1, new Rect(0, 0, image1.Width, image1.Height));
// Draw the second image on top
ctx.DrawImage(image2, r);
}
// Render the visual into a RenderTargetBitmap
RenderTargetBitmap renderBitmap = new RenderTargetBitmap(
(int)Math.Max(image1.PixelWidth, image2.PixelWidth),
(int)Math.Max(image1.PixelHeight, image2.PixelHeight),
96, 96, PixelFormats.Pbgra32);
renderBitmap.Render(visual);
return renderBitmap;
}
}
然后您可以在代码中使用该扩展。示例:
// Load data into image 1
BitmapImage bmp1 = new BitmapImage();
bmp1.BeginInit();
bmp1.UriSource = new Uri("your path goes here");
bmp1.EndInit();
image1.Source = bmp1;
// Load data into image 2
BitmapImage bmp2 = new BitmapImage();
bmp2.BeginInit();
bmp2.UriSource = new Uri("your path goes here");
bmp2.EndInit();
image2.Source = bmp2;
// Merge image 2 into image 1
image1.Merge(image2, new Rect(15, 15, 100, 100));
image1
现在将显示 image1
和 image2
。