具体实现代码如下:
1、新建一个一般处理程序: Image.ashx
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Net;
using System.Drawing.Imaging;
using System.IO; namespace Test
{
/// <summary>
///测试图片以二进制字节输出到HTML页面(显示成图片)
/// </summary>
public class Image : IHttpHandler
{ public void ProcessRequest(HttpContext context)
{
//方法一:
//WebRequest wreq = WebRequest.Create("http://img.baidu.com/video/img/video_logo_new.gif");
//HttpWebResponse wresp = (HttpWebResponse)wreq.GetResponse();
//Stream s = wresp.GetResponseStream();
//System.Drawing.Image img;
//img = System.Drawing.Image.FromStream(s);
////下面直接输出
//MemoryStream ms = new MemoryStream();
//img.Dispose(); //关键代码
//context.Response.ClearContent();
//context.Response.ContentType = "image/gif";
//context.Response.BinaryWrite(ms.ToArray()); //方法二:
WebClient my = new WebClient();
byte[] mybyte;
mybyte = my.DownloadData("http://img.baidu.com/video/img/video_logo_new.gif");
MemoryStream ms = new MemoryStream(mybyte);
System.Drawing.Image img;
img = System.Drawing.Image.FromStream(ms);
//关键代码
context.Response.ClearContent();
context.Response.ContentType = "image/gif";
context.Response.BinaryWrite(mybyte);
} public bool IsReusable
{
get
{
return false;
}
}
}
}
2、新建一个HTML页面:ImageTest.htm
<!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>
使用:Response.BinaryWrite 二进制字符串方式输出图片:<br />
主要:图片 img标签路径(src)要指向那个(Image.ashx)一般处理程序<br />
<img src="Image.ashx"/>
</body>
</html>