Introduction
I don't think this small piece of code needs a big introduction. Easy to use for anyone who just started C# programming.
Background
One day I just rattled around and thought to myself it would be nice to have a small easy helper method/class that makes it easy to download images from the web. Here it is. Ready and easy for use.
Using the code
I left out namespace on purpose because I am sure everyone wants to write their own namespace anyway.
Here is the code just to paste into a new class in your IDE:
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.IO;
using System.Net;
public class DownloadImage {
private string imageUrl;
private Bitmap bitmap;
public DownloadImage(string imageUrl) {
this.imageUrl = imageUrl;
}
public void Download() {
try {
WebClient client = new WebClient();
Stream stream = client.OpenRead(imageUrl);
bitmap = new Bitmap(stream);
stream.Flush();
stream.Close();
}
catch (Exception e) {
Console.WriteLine(e.Message);
}
}
public Bitmap GetImage() {
return bitmap;
}
public void SaveImage(string filename, ImageFormat format) {
if (bitmap != null) {
bitmap.Save(filename, format);
}
}
}
Hope this makes it easier for people.
Points of Interest
Easy and fast use of code?
History
Added .Flush() and .Close().