图像src不显示处理程序提供的外部图像

时间:2012-04-26 13:30:10

标签: c# asp.net

我有一个处理器,可以从外部网站提供图像。这本身就很好。

但是当我在图像src属性中使用处理程序时,它不起作用。

这是我对处理程序的调用:

<img src="myhandler.ashx?image=http://nssdc.gsfc.nasa.gov/image/planetary/venus/gal_venus_37218.jpg" / >

这是处理程序的代码:

using System;
using System.Collections;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Services;
using System.Web.Services.Protocols;
using System.Xml.Linq;
using System.Drawing;
using System.Net;
using System.IO;
using System.Drawing.Imaging;

namespace MumsChoice.Portal.UI.Handlers
{
    /// <summary>
    /// Summary description for $codebehindclassname$
    /// </summary>
    [WebService(Namespace = "http://tempuri.org/")]
    [WebServiceBinding(ConformsTo = WsiProfiles.BasicProfile1_1)]
    public class ExternalImageHandler : IHttpHandler
    {

        public void ProcessRequest(HttpContext context)
        {
            Bitmap bitOutput = null;
            Stream stream = null;
            string contentType = string.Empty;
            try
            {
                WebRequest req = WebRequest.Create(context.Request.QueryString["image"]);
                WebResponse response = req.GetResponse();
                contentType = response.ContentType;
                stream = response.GetResponseStream();
                bitOutput = new Bitmap(stream);
            }
            catch
            {
                bitOutput.Dispose();
            }
            finally
            {
                stream.Close();
                stream.Dispose();
                stream = null;
            }

            ImageFormat format;
            switch (contentType)
            {
                case "image/png":
                    format = ImageFormat.Png;
                    break;
                case "image/gif":
                    format = ImageFormat.Gif;
                    break;
                default:
                    format = ImageFormat.Jpeg;
                    break;
            }

            context.Response.ContentType = contentType;
            bitOutput.Save(context.Response.OutputStream, format);
            bitOutput.Dispose();
            return;  
        }


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

知道为什么吗?

1 个答案:

答案 0 :(得分:-1)

尝试在最后添加:

Response.Flush();
Response.End();