我需要将图像转换为位图.
最初,gif以字节形式读入,然后转换为Image.
但是,当我尝试将图像转换为位图时,我的图片框中显示的图形在以前是白色时具有黑色背景.
这是代码:
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;
Run Code Online (Sandbox Code Playgroud)
有人可以解释为什么背景会变黑以及我如何阻止它这样做.
谢谢
using (var bmp = new Bitmap(image.Width, image.Height, PixelFormat.Format32bppArgb))
using (var g = Graphics.FromImage(bmp))
{
g.Clear(Color.Transparent);
g.DrawImage(image, 0, 0);
bmp.Save("image.bmp", ImageFormat.Bmp);
}
Run Code Online (Sandbox Code Playgroud)
问题应该是明确的:为什么保存到BMP 会将透明度变为黑色,而保存到PNG 会保留它?
只是为了澄清:图像采用Format8bppIndexed格式,其调色板确实包含透明色(例如,它正确地绘制在窗体/图片框上)
编辑:我的错,Bitmap.Save()实际上以Format32bppRgb格式保存BMP ,即使位图格式是Format32bppArgb.