Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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 file.

Notice save this to a file and then open it is not one of my options also i'm using ItextSharp

here is my code :

Dim rect As iTextSharp.text.Rectangle
        rect = iTextSharp.text.PageSize.LETTER
        Dim x As PDFDocument = New PDFDocument("chart", rect, 1, 1, 1, 1)

        x.UserName = objCurrentUser.FullName
        x.WritePageHeader(1)
        For i = 0 To chartObj.Count - 1
            Dim chartLink as string = "http://localhost/image.gif"
            x.writechart( ** it only accept system.darwing.image ** ) 

        Next

        x.WritePageFooter()
        x.Finish(False)
like image 458
Mina Gabriel Avatar asked Aug 03 '12 18:08

Mina Gabriel


2 Answers

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)
like image 50
Varius Avatar answered Nov 20 '22 16:11

Varius


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

like image 19
T_D Avatar answered Nov 20 '22 17:11

T_D