如何将MemoryStream绑定到asp:image控件?

时间:2020-03-05 18:48:30  来源:igfitidea点击:

有没有办法将MemoryStream绑定到asp:image控件?

解决方案

回答

最好的选择是创建一个将返回图像的HttpHandler。然后将asp:Image上的ImageUrl属性绑定到HttpHandler的URL。

这是一些代码。

首先创建HttpHandler:

<%@ WebHandler Language="C#" Class="ImageHandler" %>

using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Web;

public class ImageHandler : IHttpHandler
{    
    public void ProcessRequest (HttpContext context)
    {
        context.Response.Clear();

        if (!String.IsNullOrEmpty(context.Request.QueryString["id"]))
        {
            int id = Int32.Parse(context.Request.QueryString["id"]);

            // Now you have the id, do what you want with it, to get the right image
            // More than likely, just pass it to the method, that builds the image
            Image image = GetImage(id);

            // Of course set this to whatever your format is of the image
            context.Response.ContentType = "image/jpeg";
            // Save the image to the OutputStream
            image.Save(context.Response.OutputStream, ImageFormat.Jpeg);
        }
        else
        {
            context.Response.ContentType = "text/html";
            context.Response.Write("<p>Need a valid id</p>");
        }
    }

    public bool IsReusable
    {
        get
        {
            return false;
        }
   }

   private Image GetImage(int id)
   {
       // Not sure how you are building your MemoryStream
       // Once you have it, you just use the Image class to 
       // create the image from the stream.
       MemoryStream stream = new MemoryStream();
       return Image.FromStream(stream);
   }
}

接下来,只需在我们使用asp:Image的aspx页面内调用它即可。

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!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 runat="server">
    <title></title>
</head>
<body>
    <form id="form1" runat="server">
        <div>
            <asp:Image ID="myImage" ImageUrl="~/ImageHandler.ashx?id=1" runat="server" />
        </div>
    </form>
</body>
</html>

就是这样。

回答

我假设我们需要从asp.net生成动态图像
你可能很幸运
http://www.codeplex.com/aspnet/Release/ProjectReleases.aspx?ReleaseId=16449

Hanselman最近在此发布了博客
http://www.hanselman.com/blog/ASPNETFuturesGeneratingDynamicImagesWithHttpHandlersGetsEasier.aspx

回答

虽然无法将MemoryStream数据绑定到图像,但是可以使用Label / GenericControl,一些代码和数据URI方案将图像嵌入页面中,但是这种方法存在严重问题:

Disadvantages
  
  
  Embedded content must be extracted and decoded before changes may be made, then re-encoded and re-embedded afterwards.
  Cookies are not supported.
  Information that is embedded more than once is redownloaded as part of the containing file, and thus does not benefit from the browser's cache.
  Browsers may limit URI lengths, creating an effective maximum data size. For example, URIs in previous versions of Opera had limits of 4kB, and 32kB for IE8 Beta 1[citation needed]
  Data is included as a simple stream, and many processing environments (such as web browsers) may not support using containers (such as multipart/alternative or message/rfc822) to provide greater complexity such as metadata, data compression, or content negotiation.
  Microsoft's Internet Explorer, through version 7 (some 70% of the market as of 2008 Q2), lacks support.

更好的方法是使用一个单独的" Image.aspx"页面来获取并输出MemoryStream,就像我在开始学习ASP.net时创建的相册软件中所做的那样:

(别笑,那是我第一次尝试ASP.net :-)

编辑:同意ASHX,上面的代码只是为了显示一个示例实现。当我来更新相册时,它将使用ASHX。

回答

@Will和Ben Griswald:使用" image.ashx"代替" image.aspx"。

它比完整的ASP.Net页面更轻巧,并且专门设计用于处理text / html以外的内容类型。

回答

没有。

但是我们可以创建一个特殊的页面以将该图像流式传输出去。首先,将图像的URL设置为执行流传输的页面,其中包括一些URL参数,这些参数使我们知道从何处获取图像:

<img src="GetImage.aspx?filename=foo" ... />

在GetImage.aspx中,我们可以从URL获取文件名(或者其他名称),将图像加载到MemoryStream中,然后将该内存流的内容直接写入HttpResponse:

response.Expires = 0;
    response.Buffer = false;
    response.Clear();
    response.ClearHeaders();
    response.ClearContent();
    response.ContentType = "image/jpeg";
    response.BinaryWrite(stream);
    response.Flush();
    response.Close();

回答

处理程序可以像其他任何请求一样接受url参数。因此,不是将<asp:image />链接到image.ashx,而是将其设置为image.ashx?ImageID = [此处为图像ID]。