在WPF中将png图像合并为单个图像

时间:2013-02-02 12:30:45

标签: c# wpf png imaging tiling

我正在寻找一种方法将一些PNG平铺图像合并为一个大图像。所以我搜索并找到了一些链接。 This未得到正确回答。 This不是平铺,它适用于覆盖图像,this不使用WPF。所以我正在提出这个问题。

问题定义:

我有4张PNG图片。我想将它们合并为一个PNG图像,就像这个

-------------------
|        |        |
|  png1  |  png2  |
|        |        |
-------------------
|        |        |
|  png3  |  png4  |
|        |        |
-------------------

问题:

最好和最有效的方法是什么(生成的图像必须是PNG)?

1 个答案:

答案 0 :(得分:15)

// Loads the images to tile (no need to specify PngBitmapDecoder, the correct decoder is automatically selected)
BitmapFrame frame1 = BitmapDecoder.Create(new Uri(path1), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
BitmapFrame frame2 = BitmapDecoder.Create(new Uri(path2), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
BitmapFrame frame3 = BitmapDecoder.Create(new Uri(path3), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();
BitmapFrame frame4 = BitmapDecoder.Create(new Uri(path4), BitmapCreateOptions.None, BitmapCacheOption.OnLoad).Frames.First();

// Gets the size of the images (I assume each image has the same size)
int imageWidth = frame1.PixelWidth;
int imageHeight = frame1.PixelHeight;

// Draws the images into a DrawingVisual component
DrawingVisual drawingVisual = new DrawingVisual();
using (DrawingContext drawingContext = drawingVisual.RenderOpen())
{
    drawingContext.DrawImage(frame1, new Rect(0, 0, imageWidth, imageHeight));
    drawingContext.DrawImage(frame2, new Rect(imageWidth, 0, imageWidth, imageHeight));
    drawingContext.DrawImage(frame3, new Rect(0, imageHeight, imageWidth, imageHeight));
    drawingContext.DrawImage(frame4, new Rect(imageWidth, imageHeight, imageWidth, imageHeight));
}

// Converts the Visual (DrawingVisual) into a BitmapSource
RenderTargetBitmap bmp = new RenderTargetBitmap(imageWidth * 2, imageHeight * 2, 96, 96, PixelFormats.Pbgra32);
bmp.Render(drawingVisual);

// Creates a PngBitmapEncoder and adds the BitmapSource to the frames of the encoder
PngBitmapEncoder encoder = new PngBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(bmp));

// Saves the image into a file using the encoder
using (Stream stream = File.Create(pathTileImage))
    encoder.Save(stream);