将图像转换为位图将背景变成黑色
我需要将图像转换为位图。
最初,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;
有人可以解释为什么背景变黑以及我如何阻止它这样做吗?
谢谢
I need to convert an Image to a bitmap.
initially a gif was read in as bytes and then converted to an Image.
But when I try convert the image to a bit map, the graphic displaying in my picturebox has a black background when it used to be white.
Here is the code:
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;
Can some one explain why the background is going black and how i can stop it doing this.
Thanks
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
不要另存为位图文件。该文件格式不支持透明度,因此保存的图像将不具有透明度。
您可以改用 PNG 文件格式。这将保持透明度。
如果你确实需要它使用位图文件格式,你必须先将其设置为不透明。创建一个具有相同大小的新位图,使用
Graphics.FromImage
方法获取要在图像上绘制的图形对象,使用Clear
方法将其填充为背景您想要的颜色,使用DrawImage
方法在背景上绘制图像,然后保存该位图。Don't save as a bitmap file. The file format doesn't support transparency, so the image will be saved without transparency.
You can use the PNG file format instead. That will preserve the transparency.
If you really need it to use the bitmap file format, you have to make it non-transparent first. Create a new bitmap with the same size, use the
Graphics.FromImage
method to get a graphics object to draw on the image, use theClear
method to fill it with the background color that you want, use theDrawImage
method to draw your image on top of the background, and then save that bitmap.System.Drawing.Bitmap
和位图文件格式之间存在差异。您可以保存带有透明层的System.Drawing.Bitmap
,因为它完全支持它。bmp
文件格式还可以以特定方式支持透明度。阅读本文。There is a difference between
System.Drawing.Bitmap
and Bitmap file format. You can save aSystem.Drawing.Bitmap
with transparency layer because it fully supports it.A
bmp
file format can also support transparency in particular ways. Read this.