如何保存图像控制图像?

时间:2013-09-17 13:24:32

标签: c# asp.net image webclient

我创建了一个图像控件,它使用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

有没有其他方法或解决这个问题?

1 个答案:

答案 0 :(得分: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();

希望这有帮助。