生成透明PNG c#

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/1394297/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-06 16:02:08  来源:igfitidea点击:

Generate transparent PNG c#

c#pngtransparency

提问by nLL

I have the function below to generate a sample logo. What I want to do is to return a transparent png or gif instead of a white background.

我有以下功能来生成示例徽标。我想要做的是返回一个透明的 png 或 gif 而不是白色背景。

How can I do that?

我怎样才能做到这一点?

private Bitmap CreateLogo(string subdomain)
{
    Bitmap objBmpImage = new Bitmap(1, 1);
    int intWidth  = 0;
    int intHeight = 0;
    Font objFont = new Font(
        "Arial", 
        13, 
        System.Drawing.FontStyle.Bold, 
        System.Drawing.GraphicsUnit.Pixel);

    Graphics objGraphics = Graphics.FromImage(objBmpImage);
    intWidth  = (int)objGraphics.MeasureString(subdomain, objFont).Width;
    intHeight = (int)objGraphics.MeasureString(subdomain, objFont).Height;

    objBmpImage = new Bitmap(objBmpImage, new Size(intWidth, intHeight));
    objGraphics = Graphics.FromImage(objBmpImage);
    objGraphics.Clear(Color.White);
    objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
    objGraphics.DrawString(
        subdomain, objFont, 
        new SolidBrush(Color.FromArgb(102, 102, 102)), 0, 0);

    objGraphics.Flush();
    return (objBmpImage);
}

Here is the end result:

这是最终结果:

context.Response.ContentType = "image/png";
using (MemoryStream memStream = new MemoryStream()) 
{ 
    CreateLogo(_subdname).Save(memStream, ImageFormat.Png); 
    memStream.WriteTo(context.Response.OutputStream); 
}

In the CreateLogofunction:

CreateLogo函数中:

  • objGraphics.Clear(Color.White)was changed to objGraphics.Clear(Color.Transparent)
  • new SolidBrush(Color.FromArgb(102, 102, 102))changed to new SolidBrush(Color.FromArgb(255, 255, 255))
  • objGraphics.Clear(Color.White)改为 objGraphics.Clear(Color.Transparent)
  • new SolidBrush(Color.FromArgb(102, 102, 102))变成 new SolidBrush(Color.FromArgb(255, 255, 255))

回答by Tim Croydon

You can do something like this:

你可以这样做:

Bitmap bmp = new Bitmap(300, 300);
Graphics g = Graphics.FromImage(bmp);

g.Clear(Color.Transparent);
g.FillRectangle(Brushes.Red, 100, 100, 100, 100);

g.Flush();
bmp.Save("test.png", System.Drawing.Imaging.ImageFormat.Png);