C# Programming > Drawing

C# Load Image from URL

Web Images

Loading an image from a URL in C# is possible without much code. Downloading images off the internet can be done directly to memory without having to save them as a file. The image in memory can be written to disk later if necessary.

The code to get images from a URL will work for image formats that .NET Framework supports, which is general most formats in the internet.

Image Data

The most complicated part of the source code is actually getting the image byte data from the URL. I'm going to download the byte data with .NET Framework libraries. We can do this because a URL image is just a file. Thus we can read the byte data.

Normally the image file could just be downloaded and saved directly to the hard drive. Once saved, we could load the image and display it in the C# application.

But in this case we are going to preserve the image data as bytes, which will allow our application to load any image from the internet without having to save it.

Loading the Image

The trick to loading the data as a .NET image is to wrap the raw data as a Stream. The System.IO namespace in C# has a useful class called MemoryStream. The MemoryStream C# class can be loaded with raw data that will be read like any other "file" stream, except the bytes are in memory.

Next is to use the static function FromStream to read the stream into a .NET image:

byte[] imageData = DownloadData(Url); //DownloadData function from here
MemoryStream stream = new MemoryStream(imageData);
Image img = Image.FromStream(stream);

Back to C# Article List