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 

Now I want to save the image from this image control when I use the WebClient as below

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

it gives the error of Illegal Path. That is understandable because path is ~/Handler1.ashx?id=1 for image url.

so is there any other way or work around this?

4

1 に答える 1