2009-09-08 23 views
5

Tengo la función siguiente para generar un logotipo de muestra. Lo que quiero hacer es devolver un png transparente o un gif en lugar de un fondo blanco. ¿Cómo puedo hacerlo?Generar PNG transparente C#

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


} 

aquí es el resultado final

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

función

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

} 

Respuesta

11

Usted puede hacer algo como esto:

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