c#Bitmap.Save transparancy不保存在png中

我正在尝试将具有透明度的Bitmap类保存为具有透明度的png文件。 我没有运气。

位图具有透明度,它只是不保存透明度。

这就是我正在做的事情

位图设置

Bitmap ret = new Bitmap(bWidth, bHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 

saveing

 ret.Save(filename, ImageFormat.Png); 

我也尝试用文件流保存文件,这没有任何区别。

当图像在图片框中时,透明度存在,但是当我保存时,我只得到一个黑色背景。

我真的不想使用任何第三方代码,他们找到了一种方法,我也想。

谢谢。

你确定Bitmap的像素格式是System.Drawing.Imaging.PixelFormat.Format32bppArgb吗? 我只是偶然发现了这个问题,因为我遇到了同样的问题,但这是因为我正在加载一个没有像素格式的alpha分量的图像。 我做到了

  Bitmap output = original.Clone(rect, System.Drawing.Imaging.PixelFormat.Format32bppArgb); 

并使用alpha组件正确保存了PNG。

此外,如果您正在使用MakeTransparent(),请确保您的图像中存在透明的颜色。

我已经完成图像编辑/保存已经有一段时间但是如果我记得正确的PNG与大多数人不同。 我认为你必须使用一个实际的FileStream。

编辑:啊,在这里找到了一个例子

 FileStream imageStream= new FileStream( filename, FileMode.Create ); myBitmap.Save( imageStream, ImageFormat.Png ); imageStream.Close(); 

EDIT2:经过对此的更多研究,我认为只有在某些情况下才需要中间步骤。

也有可能因为你正在使用“MakeTransparent”它捕获一个索引的alpha,但是试图根据每个像素的实际alpha值进行保存。 您可以尝试实际设置图像的Alpha值。

原因是Bitmap类不能用于透明度。

您需要将BitmapImage

 Bitmap ret = new Bitmap(bWidth, bHeight, System.Drawing.Imaging.PixelFormat.Format32bppArgb); ret.MakeTransparent(Color.White); // Change a color to be transparent Image img = (Image) ret; img.Save(filename, ImageFormat.Png); // Correct PNG save 
 ret.MakeTransparent(...); 

您是否尝试过使用Bitmap.MakeTransparent()方法?

我只是想提醒大家,MakeTransparent,正如我在这里建议的那样, 只使特定颜色透明 。 它没有考虑argb图像的Alpha通道。 因此,alpha值为100的像素(如果与MakeTransparent提供的颜色不匹配)将不具有部分透明度。

保存为PNG需要可搜索的流,如FileStream或MemoryStream。 如果你保存到其中一个并从那里获得将有没有GDI +例外或类似。 希望这可以帮助。

Portable Network Graphhics(.png)格式支持transpareny,因此将图像集图像格式保存到ImageFormat.Png。

  //update image to database MemoryStream msImage = new MemoryStream(); imgPhoto.Save(msImage, System.Drawing.Imaging.ImageFormat.Png); byte[] Img = (byte[])msImage.ToArray(); 

因此,如果以Jpeg等任何其他格式保存,将会失去透明度。 希望能帮助到你。

虽然问题已经很久了,但仍然是代码在我这里工作。

  String jpg1 = FrameImageFilePath; String jpg2 = InnerImageFilePath; String jpg3 = OutputFilePath; Image img1 = Image.FromFile(jpg1); Image img2 = Image.FromFile(jpg2); int width = img1.Width; int height = img1.Height; Bitmap img3 = new Bitmap(img1.Width, img1.Height); Bitmap img2Resized = new Bitmap(img2, width, height); Graphics g = Graphics.FromImage(img3); g.Clear(Color.Black); g.DrawImage(img2Resized, new Point(0, 0)); g.DrawImage(img1, new Point(0, 0)); g.Dispose(); img1.Dispose(); img2.Dispose(); img3.Save(jpg3, System.Drawing.Imaging.ImageFormat.Jpeg); img3.Dispose(); 

我假设对话框的FilterIndex从0开始…但它实际上从1开始,所以我的图像使用alpha透明度保存为Gifs,而gif不支持alpha透明度。 所以我的问题实际上是对话框。