生成透明PNG c#

问题描述 投票:8回答:2

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

我该怎么做?

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);
}

这是最终结果:

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

CreateLogo功能中:

  • [objGraphics.Clear(Color.White)更改为objGraphics.Clear(Color.Transparent)] >>
  • [new SolidBrush(Color.FromArgb(102, 102, 102))更改为new SolidBrush(Color.FromArgb(255, 255, 255))] >>
  • 我具有下面的功能来生成示例徽标。我想做的是返回透明的png或gif而不是白色背景。我怎样才能做到这一点?私有位图CreateLogo(string ...

c# png transparency
2个回答

13
投票

您可以执行以下操作:

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.