2010-11-01 84 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

相关问题