我正在尝试从 .aspx 页面返回透明 GIF 以在网页中显示。我试图让图像具有透明度,但我只是让图像应该透明的地方变成黑色。
有人知道我做错了什么吗?
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
最佳答案
是的,正如 Jerome 所说,无论如何都无法使用 Bitmap 对象创建透明 GIF。糟糕!
好吧,无论如何,我更改了代码来生成 PNG,并且一切都按预期工作。
由于您无法将 PNG 直接写入 OutputStream,因此我确实需要做一项小工作。我需要将 PNG 写入 MemoryStream,然后将其写入 OutputStream。
这是我的实现的最终代码:
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
关于asp.net - 如何使用 System.Drawing 绘制透明图像?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/189392/