I checked a few Chinese documents in China and found a usable Method on an English blog.
The solution code is:
Code
Copy codeThe Code is as follows:
// Save as 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 [1, 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 ;}}
}
The test html file is as follows:
Copy codeThe Code is as follows:
<! 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">
text below
</Body>
</Html>