我创建了使用 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。
那么还有其他方法或解决方法吗?