要使用asp.net动态输出透明gif图片,也就是用Response.ContentType = "image/GIF"。
查了国内几个中文资料都没解决,最后是在一个英文博客上找到一个可以用的办法。
http://www.codedblog.com/2007/08/28/generating-a-transparent-gif-image-using-c/
他的解决代码是:
代码
<%@ WebHandler Language="C#" Class="Gif" %>
using System.IO;
using System.Web;
using System.Drawing;
public class Gif : IHttpHandler {
/// <summary>
/// Returns a transparent background GIF image from the specified Bitmap.
/// </summary>
/// <param name="bitmap">The Bitmap to make transparent.</param>
/// <param name="color">The Color to make transparent.</param>
/// <returns>New Bitmap containing a transparent background gif.</returns>
public Bitmap MakeTransparentGif(Bitmap bitmap, Color color) {
byte R = color.R;
byte G = color.G;
byte B = color.B;
MemoryStream fin = new MemoryStream();
bitmap.Save(fin, System.Drawing.Imaging.ImageFormat.Gif);
MemoryStream fout = new MemoryStream((int)fin.Length);
int count = ;
byte[] buf = new byte[];
byte transparentIdx = ;
fin.Seek(, SeekOrigin.Begin);
//header
count = fin.Read(buf, , );
if ((buf[] != ) || (buf[] != ) || (buf[] != )) return null; //GIF
fout.Write(buf, , );
int i = ;
if ((buf[] & 0x80) > ) {
i = << ((buf[] & ) + ) == ? : ;
}
for (; i != ; i--) {
fin.Read(buf, , );
if ((buf[] == R) && (buf[] == G) && (buf[] == B)) {
transparentIdx = (byte)( - i);
}
fout.Write(buf, , );
}
bool gcePresent = false;
while (true) {
fin.Read(buf, , );
fout.Write(buf, , );
if (buf[] != 0x21) break;
fin.Read(buf, , );
fout.Write(buf, , );
gcePresent = (buf[] == 0xf9);
while (true) {
fin.Read(buf, , );
fout.Write(buf, , );
if (buf[] == ) break;
count = buf[];
if (fin.Read(buf, , count) != count) return null;
if (gcePresent) {
if (count == ) {
buf[] |= 0x01;
buf[] = transparentIdx;
}
}
fout.Write(buf, , count);
}
}
while (count > ) {
count = fin.Read(buf, , );
fout.Write(buf, , );
}
fin.Close();
fout.Flush();
return new Bitmap(fout);
}
public void ProcessRequest(HttpContext context) {
Bitmap transGif = null;
using (Bitmap bmp = new Bitmap(, )) {
using (Graphics g = Graphics.FromImage(bmp)) {
g.Clear(Color.Gray);
g.DrawString("transparent gif image",
new Font("verdana bold", 14f), Brushes.LemonChiffon, 0f, 0f);
bmp.MakeTransparent(Color.Gray);
transGif = MakeTransparentGif(bmp, Color.Black);
}
}
if (transGif != null) {
context.Response.Clear();
context.Response.ContentType = "image/GIF";
transGif.Save(context.Response.OutputStream,
System.Drawing.Imaging.ImageFormat.Gif);
}
}
public bool IsReusable {get {return false;}}
}
测试html文件如下
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title></title>
</head>
<body style="background:#999">
<img src="gif.ashx" style="position:absolute" />下方的文字
</body>
</html>