[英]How to make the background of an image ( logo ) transparent in C# WPF?
I've an image ( logo ) and I would like to pass it as an argument and make the background transparent and then save it.我有一个图像( logo ),我想将它作为参数传递,并使背景透明,然后保存它。
How can I achieve this?我怎样才能做到这一点?
This what I've tried:这是我尝试过的:
public string SaveImage(Bitmap bmp,string SavePath,string Name)
{
string path = "";
var format = ImageFormat.Jpeg;
using (var m = new MemoryStream())
{
bmp.Save(m, format);
var img = System.Drawing.Image.FromStream(m);
using (var g = Graphics.FromImage(img)) // This is what I've used for making the background transparent
{
g.Clear(System.Drawing.Color.Transparent);
g.Save();
}
var ImgPath = Path.Combine(SavePath, Path.ChangeExtension(Name,"png"));
img.Save(ImgPath);
path = ImgPath;
}
return path;
}
After testing this function I'm getting a black image as an output ( save image )在测试了这个 function 之后,我得到了一个黑色图像作为 output(保存图像)
Some remarks for your code:您的代码的一些注释:
System.Drawing
types wrapping native GDI+ components, not WPF.System.Drawing
类型,而不是 WPF。Bitmap
with JPEG encoder, which does not support transparency.Bitmap
。 Even if the logo had a transparent background it is removed by the JPEG encoder Possible solutions:可能的解决方案:
MakeTransparent
method instead of Clear
.MakeTransparent
方法而不是Clear
。 It will replace a single color so it is not able to restore possible anti-aliased alpha blending.GetReadWriteBitmapData
extension method on a WriteableBitmap
to access the same MakeTransparent
functionality as above along with a sort of other features .WriteableBitmap
上的GetReadWriteBitmapData
扩展方法来访问与上述相同的MakeTransparent
功能以及其他一些功能。 But to restore a nicely anti-aliased alpha background you might want to use the TransformColors
method instead if you know how to separate the blended colors.TransformColors
方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.