How can I convert image url to system.drawing.image

前端 未结 6 940
爱一瞬间的悲伤
爱一瞬间的悲伤 2020-12-13 06:53

I\'m using VB.Net I have an url of an image, let\'s say http://localhost/image.gif

I need to create a System.Drawing.Image object from that

相关标签:
6条回答
  • 2020-12-13 07:17

    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)
    
    0 讨论(0)
  • 2020-12-13 07:19

    You can try this to get the Image

    Dim req As System.Net.WebRequest = System.Net.WebRequest.Create("[URL here]")
    Dim response As System.Net.WebResponse = req.GetResponse()
    Dim stream As Stream = response.GetResponseStream()
    
    Dim img As System.Drawing.Image = System.Drawing.Image.FromStream(stream)
    stream.Close()
    
    0 讨论(0)
  • 2020-12-13 07:26

    iTextSharp is able to accept Uri's:

    Image.GetInstance(uri)
    
    0 讨论(0)
  • 2020-12-13 07:31
    Dim c As New System.Net.WebClient
    Dim FileName As String = "c:\StackOverflow.png"
    c.DownloadFile(New System.Uri("http://cdn.sstatic.net/stackoverflow/img/sprites.png?v=5"), FileName)
    Dim img As System.Drawing.Image
    img = System.Drawing.Image.FromFile(FileName)
    
    0 讨论(0)
  • 2020-12-13 07:34

    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);
        }
    
    0 讨论(0)
  • 2020-12-13 07:39

    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

    0 讨论(0)
提交回复
热议问题