首页  ·  知识 ·  云计算
ASP.NET读取网络图片并在页面上显示
网友      编辑:dezai   图片来源:网络
ASP.NET读取网络图片并在页面上显示

<!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>
    <form id="form1" runat="server">
    <div>
        <img src="Handler.ashx?url=http://www.google.com.hk/intl/zh-CN/images/logo_cn.png"
            alt="google logo" />
    </div>
    </form>
</body>
</html>

Handler.ashx

<%@ WebHandler Language="C#" Class="Handler" %>
using System;
using System.Web;
using System.Net;
using System.Drawing;
using System.IO;

public class Handler : IHttpHandler {
   
    public void ProcessRequest (HttpContext context) {
        string imgUrl = context.Request["Url"];
        if (!string.IsNullOrEmpty(imgUrl))
        {
            Uri myUri = new Uri(imgUrl);
            WebRequest webRequest = WebRequest.Create(myUri);
            WebResponse webResponse = webRequest.GetResponse();
            Bitmap myImage = new Bitmap(webResponse.GetResponseStream());

            MemoryStream ms = new MemoryStream();
            myImage.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
            context.Response.ClearContent();
            context.Response.ContentType = "image/Jpeg";
            context.Response.BinaryWrite(ms.ToArray());
        }
    }

    public bool IsReusable {
        get {
            return false;
        }
    }
}

本文作者:网友 来源:网络
CIO之家 www.ciozj.com 微信公众号:imciow
    >>频道首页  >>网站首页   纠错  >>投诉
版权声明:CIO之家尊重行业规范,每篇文章都注明有明确的作者和来源;CIO之家的原创文章,请转载时务必注明文章作者和来源;
延伸阅读