80

I have a hyperlink which has a image.

I need to read/load the image from that hyperlink and assign it to a byte array (byte[]) in C#.

Thanks.

Ben
  • 54,723
  • 49
  • 178
  • 224
Sharpeye500
  • 8,775
  • 25
  • 95
  • 143

3 Answers3

177

WebClient.DownloadData is the easiest way.

string someUrl = "http://www.google.com/images/logos/ps_logo2.png"; 
using (var webClient = new WebClient()) { 
    byte[] imageBytes = webClient.DownloadData(someUrl);
}
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Josh
  • 68,005
  • 14
  • 144
  • 156
13

If you need an asynchronous version:

using (var client = new HttpClient())
{
    using (var response = await client.GetAsync(url))
    {
        byte[] imageBytes =
            await response.Content.ReadAsByteArrayAsync().ConfigureAwait(false);
    }
}
Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992
Dunc
  • 18,404
  • 6
  • 86
  • 103
4

.NET 4.5 introduced WebClient.DownloadDataTaskAsync() for async usage.

Example:

using ( WebClient client = new WebClient() )
{
  byte[] bytes = await client.DownloadDataTaskAsync( "https://someimage.jpg" );
}

Christo Carstens
  • 741
  • 7
  • 14