wpf 在WPF中将png图像合并为单个图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/14661919/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Merge png images into single image in WPF
提问by Hossein Narimani Rad
I'm looking for a way to Merge some PNG tile images into a big image. So I search and found some links. Thisis not answered properly. Thisis not tiling, it's good for overlaying images and thisis not using WPF. So I'm making this question.
我正在寻找一种将一些 PNG 平铺图像合并为大图像的方法。所以我搜索并找到了一些链接。这没有正确回答。这不是平铺,它有利于叠加图像,而且这不是使用 WPF。所以我提出这个问题。
Problem Definition:
问题定义:
I have 4 PNG images. I want to merge them into a single PNG image, like this
我有 4 张 PNG 图片。我想将它们合并成一个 PNG 图像,就像这样
-------------------
| | |
| png1 | png2 |
| | |
-------------------
| | |
| png3 | png4 |
| | |
-------------------
Question:
题:
What is the best and efficient way of doing this (The resulting image must be PNG)?
这样做的最佳和有效方法是什么(生成的图像必须是 PNG)?
回答by Cédric Bignon
// 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);

