2013-09-17 7 views
1

Я создал управление изображением, которое динамически визуализирует ImageUrl с помощью Handler.ashxКак сохранить изображение?

кода для получения контроля изображения является

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-адреса изображения.

так есть ли какой-либо другой способ или работать вокруг этого?

ответ

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(); 

Надеюсь, это поможет.

+0

Это сработало благодаря –

Смежные вопросы