How can I convert image url to system.drawing.image
You could use WebClient class to download image and then MemoryStream to read it:
C#
WebClient wc = new WebClient();
byte[] bytes = wc.DownloadData("http://localhost/image.gif");
MemoryStream ms = new MemoryStream(bytes);
System.Drawing.Image img = System.Drawing.Image.FromStream(ms);
VB
Dim wc As New WebClient()
Dim bytes As Byte() = wc.DownloadData("http://localhost/image.gif")
Dim ms As New MemoryStream(bytes)
Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(ms)
You can use HttpClient and accomplish this task async with few lines of code.
public async Task<Bitmap> GetImageFromUrl(string url)
{
var httpClient = new HttpClient();
var stream = await httpClient.GetStreamAsync(url);
return new Bitmap(stream);
}
The other answers are also correct, but it hurts to see the Webclient and MemoryStream not getting disposed, I recommend putting your code in a using
.
Example code:
using (var wc = new WebClient())
{
using (var imgStream = new MemoryStream(wc.DownloadData(imgUrl)))
{
using (var objImage = Image.FromStream(imgStream))
{
//do stuff with the image
}
}
}
The required imports at top of your file are System.IO
, System.Net
& System.Drawing
In VB.net the syntax was using wc as WebClient = new WebClient() {
etc