1

Best way to load an image from url to Drawing.Image?

I found this two ways, which one is better or is there any better?

PictureBox pb = new PictureBox();
pb.ImageLocation = "http://lovelypackage.com/wp-content/uploads/2012/02/lovely-package-whatever-wine4.jpg";
Image img = pb.Image;

OR

using (WebClient wc = new WebClient())
{
    byte[] bytes = wc.DownloadData("http://lovelypackage.com/wp-content/uploads/2012/02/lovely-package-whatever-wine4.jpg");
    MemoryStream ms = new MemoryStream(bytes);
    Image img = Image.FromStream(ms);
}
a1204773
  • 6,923
  • 20
  • 64
  • 94
  • try this question: http://stackoverflow.com/questions/10077219/download-image-from-url-in-c-sharp – gunr2171 Apr 18 '13 at 20:03
  • this seems to need more work than my two ways :D I need the most optimized way.. If there is no big difference i prefer the picturebox way – a1204773 Apr 18 '13 at 20:06
  • 1
    Are you actually using the PictureBox in your program or is it literally there just to handle the image downloading for you? If you're not using the PictureBox, I'd recommend the second approach. I'd go one step further and make it a method that takes a `url` string and returns the `image` making it reusable elsewhere. – keyboardP Apr 18 '13 at 20:11
  • 1
    Also, you might want to use `DownloadDataAsync` to avoid blocking the UI thread, especially if the image may take a noticeable amount of time to download. – keyboardP Apr 18 '13 at 20:18
  • @keyboardP true.. write as answer to give u best answer – a1204773 Apr 18 '13 at 20:42

1 Answers1

2

If you're not using the PictureBox in your application, I'd recommend the second approach. I'd go one step further and make it a method that takes a url string and returns the Image making it reusable elsewhere. Also, you might want to use DownloadDataAsync to avoid blocking the UI thread, especially if the image may take a noticeable amount of time to download.

keyboardP
  • 68,824
  • 13
  • 156
  • 205