2010-11-22 23 views
2

我想使用System.Windows.Media.Imaging將兩個相同大小和格式的位圖組合成第三個相同大小和格式的文件。我在WPF的上下文之外(在LINQPad中處理代碼)這樣​​做,因爲其目的是將其作爲不受支持的System.Drawing的替代方法應用於ASP.net應用程序。複合兩個位圖與System.Windows.Media.Imaging

// 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); 
} 

這會創建一個與從layerOne加載的文件相同的文件,我期待的是將layerTwo覆蓋在layerOne上。看來正在發生的事情是數據被寫入BackBuffer,但從未被渲染到位圖上......可能這是調度員通常會做的事情。

我哪裏錯了?我怎樣才能回到正軌?

回答

3

問題出在WritePixels的第一個參數,這表示要更新WriteableBitmap的區域。

相反的Int32Rect.Empty,你可以不喜歡以下內容,應該看到寫在第一第二圖像:

Int32Rect sourceRect = new Int32Rect(0, 0, (int)layerTwo.Width, (int)layerTwo.Height); 
composite.WritePixels(sourceRect, pixels, stride, 0); 
+0

這似乎是解決方案,還有一些其他的問題,但我懷疑,我需要多做一些思考。有趣的是,我認爲Int32Rect.Empty是整個位圖的簡寫,儘管這似乎只適用於CopyPixels。 – 2010-11-23 18:24:52