1

我创建了使用 Handler.ashx 动态呈现 ImageUrl 的图像控件

获取图像控件的代码是

public class Handler1 : 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)
    {
        byte[] data= File.ReadAllBytes(@"C:\Users\Public\Pictures\Sample Pictures\Desert.jpg");
        MemoryStream stream = new MemoryStream(data);
        return Image.FromStream(stream);
    }
}

Aspx 代码是

<asp:Image ID="image1" ImageUrl="~/Handler1.ashx?id=1" runat="server"></asp:Image>//The image url is given in code behind here set as an example 

WebClient现在,当我使用以下内容时,我想从此图像控件中保存图像

using (WebClient client = new WebClient())
{
   client.DownloadFile(image1.ImageUrl, "newimage.jpg");
}

它给出了 的错误Illegal Path。这是可以理解的,因为路径是~/Handler1.ashx?id=1图像 url。

那么还有其他方法或解决方法吗?

4

1 回答 1

0

您可以使用Session保存图像字节,然后从会话访问该字节数组,然后写入作为对客户端浏览器的响应,如下所示

在你的助手中添加一行

Session["ImageBytes"] = data;

然后在你的任何控件事件中把这个假设放在按钮点击上

byte[] imagedata =(byte[]) Session["ImageBytes"];
string attachment = "attachment; filename="+txtJobNumber.Text+"_Image.jpg";
HttpContext.Current.Response.Clear();
HttpContext.Current.Response.ClearHeaders();
HttpContext.Current.Response.ClearContent();
HttpContext.Current.Response.AddHeader("content-disposition", attachment);
HttpContext.Current.Response.ContentType = "image/jpeg";
HttpContext.Current.Response.AddHeader("Pragma", "public");
HttpContext.Current.Response.BinaryWrite(imagedata);
HttpContext.Current.Response.Flush();
HttpContext.Current.Response.Close();

希望这可以帮助。

于 2013-09-17T13:49:01.723 回答