当前位置:  开发笔记 > 编程语言 > 正文

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

如何解决《如何将MemoryStream绑定到asp:image控件?》经验,为你挑选了2个好方法。

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



1> Dale Ragan..:

最好的办法是创建一个可以返回图像的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("

Need a valid id

"); } } 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" %>





    


    

就是这样.



2> Joel Coehoor..:

处理程序可以像任何其他请求一样接受url参数.因此,不要将您链接image.ashx您的设置image.ashx?ImageID=[Your image ID here].

推荐阅读
雯颜哥_135
这个屌丝很懒,什么也没留下!
DevBox开发工具箱 | 专业的在线开发工具网站    京公网安备 11010802040832号  |  京ICP备19059560号-6
Copyright © 1998 - 2020 DevBox.CN. All Rights Reserved devBox.cn 开发工具箱 版权所有