2010-11-01 81 views
9

我需要將圖像轉換爲位圖。將圖像轉換爲位圖將背景黑色

最初一個gif以字節讀入,然後轉換爲圖像。

但是,當我嘗試將圖像轉換爲位圖時,在我的圖片框中顯示的圖形過去是白色時會顯示黑色背景。

下面是代碼:

var image = (System.Drawing.Image)value; 
     // Winforms Image we want to get the WPF Image from... 
     var bitmap = new System.Windows.Media.Imaging.BitmapImage(); 
     bitmap.BeginInit(); 
     MemoryStream memoryStream = new MemoryStream(); 
     // Save to a memory stream... 
     image.Save(memoryStream, ImageFormat.Bmp); 
     // Rewind the stream... 
     memoryStream.Seek(0, System.IO.SeekOrigin.Begin); 
     bitmap.StreamSource = memoryStream; 
     bitmap.EndInit(); 
     return bitmap; 

有人能解釋爲什麼背景是怎麼回事黑,我怎麼能阻止它這樣做。

謝謝

回答

21

不保存爲位圖文件。該文件格式不支持透明度,所以圖像將被保存而沒有透明度。

您可以改用PNG文件格式。這將保持透明度。

如果你真的需要它來使用位圖文件格式,你必須首先使它不透明。創建一個具有相同大小的新位圖,使用Graphics.FromImage方法獲取要在圖像上繪製的圖形對象,使用Clear方法將其填充所需的背景顏色,使用DrawImage方法在您的圖像上繪製圖像背景,然後保存該位圖。

+0

非常感謝。像魅力一樣工作 – SetiSeeker 2010-11-01 08:41:42

+0

也適合我。 Theres一些代碼顯示這個解決方案在這裏:http://stackoverflow.com/questions/6513633/convert-transparent-png-to-jpg-with-non-black-background-color – TripleAntigen 2016-04-30 04:17:48

+0

但BMP確實支持透明度它不? – Robula 2017-06-28 09:59:12

相關問題