raki
raki

Reputation: 2293

Image Loading in c# from a web URL

am trying to display an image in a "toolStrip" i c# from a weburl. Am using the following methode to get the image

WebRequest requestPic5 = WebRequest.Create(icon_path);
                         requestPic5.Timeout = 5000;
                         WebResponse responsePic5 = null;
                         Image Myimg5 = null;

if (requestPic5 != null)
   {
      responsePic5 = requestPic5.GetResponse();
      if (responsePic5 != null)
         {
            Myimg5 = Image.FromStream(responsePic5.GetResponseStream());
          }
   }

its failing when Myimg5 = Image.FromStream(responsePic5.GetResponseStream()); throws an exception but the image is still there in the url

But unfortunately most of the time its not loading properly and sometimes throwing a 404 error

Upvotes: 5

Views: 8435

Answers (2)

Xaqron
Xaqron

Reputation: 30837

Probably the website is protected against hot linking. Since images are large in size in compare to html pages and websites pays for their used bandwidth, this is a mechanism for protecting websites from bsndwidth theft, by other websites.

The idea is using some kind of authentication and make sure a real user is asking for the image. This is usually done by cookies on the page which contains the image. You need to get those cookies and send them with your request. You need to add a CookieContainer to your request, then request the page the image resides and at the end retrieve the image (use the same request for all steps, cookies would be added and used automatically).

Upvotes: 0

danielpops
danielpops

Reputation: 731

The response stream has other stuff that you don't necessarily want. You really just want the raw data of the imgage file, so you can use:

new MemoryStream(new WebClient().DownloadData("http://address/file.ico"));

Upvotes: 6

Related Questions