Monday, December 29, 2008

How to Load an Image from the Internet

I built a simple web page that allows one to listen to radio stations from across Canada:

At first I was loading each station's logo from its parent website. Some were quite large so I had to do a check to determine its dimensions. My first inclination was to use this method:

System.Drawing.Image.FromFile

But I quickly learned that it was only useful for images stored on the local server's hard drive. It wouldn't work for remote ones. To get that working was a bit tricky, but I finally realized this to be the solution:

// Retrieve the actual dimensions of the logo image
System.Drawing.Image actualImage = System.Drawing.Image.FromStream( System.Net.HttpWebRequest.Create(logoUrl).GetResponse().GetResponseStream());

// Keep the image logo to a maximum of 200 pixels tall
if (actualImage.Height > 200)
imageLogo.Width = actualImage.Width * (int)imageLogo.Height.Value / actualImage.Height;

No comments:

Post a Comment