Steven
Steven

Reputation: 18869

Render image to a page

I have a page http://www.mysite.com/image.aspx, that I want to load and display an image instead of rendering HTML.

I have the ContentType of the page set to image/png, and here's my code:

using (Bitmap image = new Bitmap("http://www.google.com/images/img.png"))
{
    using (MemoryStream ms = new MemoryStream())
    {
        image.Save(ms, System.Drawing.Imaging.ImageFormat.Png);
        ms.WriteTo(Response.OutputStream);
    }
}

But I get an error saying:

URI formats are not supported.

How can I load an external image and render it to the page?

Upvotes: 0

Views: 304

Answers (1)

Tejs
Tejs

Reputation: 41256

You can't load a Bitmap using a URI - it has to be a local file to your computer.

If you want to load an image from off the web and then render it, you need to make a web request off to that specific resource and then render the bytes to the stream as you are doing.

AKA

WebRequest webRequest = WebRequest.Create("http://www.google.com/images/img.png");
using(WebResponse response = webRequest.GetResponse())
{
    using(MemoryStream stream = new MemoryStream(response.GetResponseStream())
    {
         stream.WriteTo(Response.OutputStream);
    }
}

Upvotes: 4

Related Questions