2008-10-09 26 views
10

Estoy tratando de devolver un GIF transparente desde una página .aspx para visualizar dentro de una página web. Intento que la imagen tenga transparencia, pero sigo haciendo que el Negro esté donde la imagen debe ser Transparente.¿Cómo se dibuja una imagen transparente usando System.Drawing?

¿Alguien sabe lo que estoy haciendo mal?

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ 
    Handles Me.Load 
    '' Change the response headers to output a GIF image. 
    Response.Clear() 
    Response.ContentType = "image/gif" 

    Dim width = 110 
    Dim height = width 

    '' Create a new 32-bit bitmap image 
    Dim b = New Bitmap(width, height) 

    '' Create Grahpics object for drawing 
    Dim g = Graphics.FromImage(b) 

    Dim rect = New Rectangle(0, 0, width - 1, height - 1) 

    '' Fill in with Transparent 
    Dim tbrush = New System.Drawing.SolidBrush(Color.Transparent) 
    g.FillRectangle(tbrush, rect) 

    '' Draw Circle Border 
    Dim bPen = Pens.Red 
    g.DrawPie(bPen, rect, 0, 365) 

    '' Fill in Circle 
    Dim cbrush = New SolidBrush(Color.LightBlue) 
    g.FillPie(cbrush, rect, 0, 365) 


    '' Clean up 
    g.Flush() 
    g.Dispose() 

    '' Make Transparent 
    b.MakeTransparent() 

    b.Save(Response.OutputStream, Imaging.ImageFormat.Gif) 
    Response.Flush() 
    Response.End() 
End Sub 
+0

Eliminé mi publicación por lo que no llena todo esto. – mattlant

Respuesta

5

Desafortunadamente, no existe una manera fácil de crear un Gif transparente utilizando un objeto Bitmap. (Consulte this KB article)

Alternativamente, puede usar el formato PNG que admita transparencia con el código que está utilizando.

6

Sí, como dijo Jerome, no hay forma de crear GIF transparentes utilizando un objeto Bitmap. ¡Mierda!

Bueno, de todos modos, cambié mi código para generar un PNG y todo funciona como se esperaba.

Hay una pequeña solución que tuve que hacer, ya que no puede escribir archivos PNG directamente en OutputStream. Necesitaba escribir el archivo PNG en un MemoryStream y luego escribirlo en OutputStream.

Aquí está el código final para mi aplicación:

Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) _ 
    Handles Me.Load 
    '' Change the response headers to output a JPEG image. 
    Response.Clear() 
    Response.ContentType = "image/png" 

    Dim width = 11 
    Dim height = width 

    '' Create a new 32-bit bitmap image 
    Dim b = New Bitmap(width, height) 

    '' Create Grahpics object for drawing 
    Dim g = Graphics.FromImage(b) 

    '' Fill the image with a color to be made Transparent after drawing is finished. 
    g.Clear(Color.Gray) 

    '' Get rectangle where the Circle will be drawn 
    Dim rect = New Rectangle(0, 0, width - 1, height - 1) 

    '' Draw Circle Border 
    Dim bPen = Pens.Black 
    g.DrawPie(bPen, rect, 0, 365) 

    '' Fill in Circle 
    Dim cbrush = New SolidBrush(Color.Red) 
    g.FillPie(cbrush, rect, 0, 365) 

    '' Clean up 
    g.Flush() 
    g.Dispose() 

    '' Make Transparent 
    b.MakeTransparent(Color.Gray) 

    '' Write PNG to Memory Stream then write to OutputStream 
    Dim ms = New MemoryStream() 
    b.Save(ms, Imaging.ImageFormat.Png) 
    ms.WriteTo(Response.OutputStream) 

    Response.Flush() 
    Response.End() 
End Sub 
4

Es posible, pero no es fácil
Si usted es capaz de utilizar código no seguro en su proyecto, existen algunos métodos para utilice punteros para desgarrar la tabla de colores y hacer que la transparencia funcione.

Una aplicación de formularios de muestra de Bob Powell está disponible aquí http://www.bobpowell.net/giftransparency.htm. Utilicé una variación de este método en un manejador web hace unos años que se estaba recibiendo aproximadamente 10 millones de veces al mes, y parecía funcionar bien.

Si solo está utilizando una paleta de colores limitada, puede reducir el procesamiento de la tabla de colores a solo los colores que necesita (no recuerdo exactamente cómo lo hice ...).

Dicho esto, png es una carga métrica más fácil.

2

aquí hay un código para transformar un gif (que ya tiene transparencia) (se supone que desea cambiar el tamaño) en mapa de bits y luego se puede mostrar correctamente con su transparencia.

imagePath = System.Web.HttpContext.Current.Request.MapPath(libraryPath + reqImageFile); 
System.Drawing.Image image = null; 
Bitmap resizedImage = null; 

if (reqWidth == 0) { reqWidth = image.Width; } 
if (reqHeight == 0) { reqHeight = image.Height; } 
image = System.Drawing.Image.FromFile(imagePath); 
reqWidth = image.Width; 
reqHeight = image.Height; 

//here is the transparency 'special' treatment 
resizedImage = new Bitmap(reqWidth, reqHeight, PixelFormat.Format8bppIndexed); 
ColorPalette pal = resizedImage.Palette; 
for (int i = 0; i < pal.Entries.Length; i++) 
{ 
     Color col = pal.Entries[i]; 
     pal.Entries[i] = Color.FromArgb(0, col.R, col.G, col.B); 
} 
resizedImage.Palette = pal; 
BitmapData src = ((Bitmap)image).LockBits(new Rectangle(0, 0, reqWidth, reqHeight), ImageLockMode.ReadOnly, image.PixelFormat); 
BitmapData dst = resizedImage.LockBits(new Rectangle(0, 0, resizedImage.Width, resizedImage.Height), 
ImageLockMode.WriteOnly, resizedImage.PixelFormat); 
((Bitmap)image).UnlockBits(src); 
resizedImage.UnlockBits(dst); 

¡Buena suerte!

Grégoire Lafortune

Cuestiones relacionadas