【问题标题】:How to save image controls image?如何保存图像控件图像?
【发布时间】:2013-09-17 13:24:32
【问题描述】:

我已经创建了使用 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 的错误。这是可以理解的,因为图像 url 的路径是 ~/Handler1.ashx?id=1

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

【问题讨论】:

    标签: c# asp.net image webclient


    【解决方案1】:

    您可以使用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();
    

    希望这会有所帮助。

    【讨论】:

      猜你喜欢
      • 2014-01-27
      • 2011-08-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-11-30
      • 2012-06-30
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多