2013-02-02 51 views
5

我正在尋找一種方法將一些PNG平鋪圖像合併爲大圖像。所以我搜索並找到了一些鏈接。 This未正確回答。 This不是平鋪,它很好的覆蓋圖像和this不使用WPF。所以我正在提出這個問題。在WPF中將png圖像合併爲單個圖像

問題定義:

我有4個PNG圖像。我想將它們合併成一個單一的PNG圖像,這樣

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

問:

什麼是這樣做(所得的圖像必須是PNG)的最好的和有效的方式?

+0

加入是一個單獨的問題,保存。一旦你有了加入的位圖,你可以將它保存爲任何支持的格式。 – ChrisF

回答

13
// 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); 
+0

爲什麼不在#1使用'PngBitmapDecoder'? –

+0

你可以顯示#4的代碼示例嗎? –

+0

@HosseinNarimaniRad我決定使用另一種方法。使用WPF! –

相關問題