具体实现代码如下:
1、新建一个一般处理程序: Image.ashx
1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Net; 6 using System.Drawing.Imaging; 7 using System.IO; 8 9 namespace Test 10 { 11 /// <summary> 12 ///测试图片以二进制字节输出到HTML页面(显示成图片) 13 /// </summary> 14 public class Image : IHttpHandler 15 { 16 17 public void ProcessRequest(HttpContext context) 18 { 19 //方法一: 20 //WebRequest wreq = WebRequest.Create("http://img.baidu.com/video/img/video_logo_new.gif"); 21 //HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse(); 22 //Stream s = wresp.GetResponseStream(); 23 //System.Drawing.Image img; 24 //img = System.Drawing.Image.FromStream(s); 25 ////下面直接输出 26 //MemoryStream ms = new MemoryStream(); 27 //img.Dispose(); 28 29 //关键代码 30 //context.Response.ClearContent(); 31 //context.Response.ContentType = "image/gif"; 32 //context.Response.BinaryWrite(ms.ToArray()); 33 34 //方法二: 35 WebClient my = new WebClient(); 36 byte[] mybyte; 37 mybyte = my.DownloadData("http://img.baidu.com/video/img/video_logo_new.gif"); 38 MemoryStream ms = new MemoryStream(mybyte); 39 System.Drawing.Image img; 40 img = System.Drawing.Image.FromStream(ms); 41 //关键代码 42 context.Response.ClearContent(); 43 context.Response.ContentType = "image/gif"; 44 context.Response.BinaryWrite(mybyte); 45 } 46 47 public bool IsReusable 48 { 49 get 50 { 51 return false; 52 } 53 } 54 } 55 }
2、新建一个HTML页面:ImageTest.htm
1 <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 2 <html xmlns="http://www.w3.org/1999/xhtml"> 3 <head> 4 <title></title> 5 </head> 6 <body> 7 使用:Response.BinaryWrite 二进制字符串方式输出图片:<br /> 8 主要:图片 img标签路径(src)要指向那个(Image.ashx)一般处理程序<br /> 9 <img src="Image.ashx"/> 10 </body> 11 </html>