欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

asp.net 动态输出透明gif图片

程序员文章站 2024-03-09 11:43:11
查了国内几个中文资料都没解决,最后是在一个英文博客上找到一个可以用的办法。他的解决代码是: 代码 复制代码 代码如下: //存成gif.ashx <%@ webhan...
查了国内几个中文资料都没解决,最后是在一个英文博客上找到一个可以用的办法。
他的解决代码是:

代码
复制代码 代码如下:

//存成gif.ashx
<%@ 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 = 0;
byte[] buf = new byte[256];
byte transparentidx = 0;
fin.seek(0, seekorigin.begin);
//header
count = fin.read(buf, 0, 13);
if ((buf[0] != 71) || (buf[1] != 73) || (buf[2] != 70)) return null; //gif
fout.write(buf, 0, 13);
int i = 0;
if ((buf[10] & 0x80) > 0) {
i = 1 << ((buf[10] & 7) + 1) == 256 ? 256 : 0;
}
for (; i != 0; i--) {
fin.read(buf, 0, 3);
if ((buf[0] == r) && (buf[1] == g) && (buf[2] == b)) {
transparentidx = (byte)(256 - i);
}
fout.write(buf, 0, 3);
}
bool gcepresent = false;
while (true) {
fin.read(buf, 0, 1);
fout.write(buf, 0, 1);
if (buf[0] != 0x21) break;
fin.read(buf, 0, 1);
fout.write(buf, 0, 1);
gcepresent = (buf[0] == 0xf9);
while (true) {
fin.read(buf, 0, 1);
fout.write(buf, 0, 1);
if (buf[0] == 0) break;
count = buf[0];
if (fin.read(buf, 0, count) != count) return null;
if (gcepresent) {
if (count == 4) {
buf[0] |= 0x01;
buf[3] = transparentidx;
}
}
fout.write(buf, 0, count);
}
}
while (count > 0) {
count = fin.read(buf, 0, 1);
fout.write(buf, 0, 1);
}
fin.close();
fout.flush();
return new bitmap(fout);
}
public void processrequest(httpcontext context) {
bitmap transgif = null;
using (bitmap bmp = new bitmap(300, 50)) {
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>