Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generate transparent PNG c#

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.

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 CreateLogo function:

  • 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))
like image 770
nLL Avatar asked Sep 08 '09 14:09

nLL


People also ask

How do I make an image have a transparent background?

Upload your picture into Fotor to get started. Then click on the Background Remover tool and Fotor will automatically convert your image into a transparent PNG within seconds. No manual editing are needed at all! Finally, click on the download icon to download your transparent PNG picture in high quality.

Can PNG have transparent pixels?

GIF and PNG‑8 formats support one level of transparency—pixels can be fully transparent or fully opaque, but not partially transparent. (By contrast, PNG‑24 format supports multilevel transparency; that is, you can have up to 256 degrees of transparency in an image, ranging from opaque to completely transparent.)


2 Answers

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);
like image 182
Tim Croydon Avatar answered Nov 04 '22 01:11

Tim Croydon


Take a look at Can you make an alpha transparent PNG with C#?

like image 33
KV Prajapati Avatar answered Nov 04 '22 03:11

KV Prajapati