生成透明的PNG c#

时间:2009-09-08 14:19:54

标签: c# png transparency

我有以下功能来生成示例徽标。我想要做的是返回透明的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); 
            }

功能

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.Transparent);
    objGraphics.SmoothingMode = System.Drawing.Drawing2D.SmoothingMode.AntiAlias;
    objGraphics.TextRenderingHint = System.Drawing.Text.TextRenderingHint.AntiAlias;
    objGraphics.DrawString(subdomain, objFont, new SolidBrush(Color.FromArgb(255, 255, 255)), 0, 0);
    objGraphics.Flush();
    return (objBmpImage);

}

2 个答案:

答案 0 :(得分:12)

您可以这样做:

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

答案 1 :(得分:4)