如何将图片网址转换为system.drawing.image

时间:2012-08-03 18:51:57

标签: c# asp.net .net vb.net itextsharp

我正在使用VB.Net我有一个图片网址,让我们说http://localhost/image.gif

我需要从该文件创建一个System.Drawing.Image对象。

注意将其保存到文件然后打开它不是我的选项之一 我也在使用ItextSharp

这是我的代码:

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)

6 个答案:

答案 0 :(得分:56)

您可以使用WebClient类下载图像,然后使用MemoryStream来读取它:

<强> 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)

答案 1 :(得分:13)

其他答案也是正确的,但看到Webclient和MemoryStream没有被处理会很痛苦,我建议您将代码放在using中。

示例代码:

using (var wc = new WebClient())
{
    using (var imgStream = new MemoryStream(wc.DownloadData(imgUrl)))
    {
        using (var objImage = Image.FromStream(imgStream))
        {
            //do stuff with the image
        }
    }
}

您文件顶部的所需导入为System.IOSystem.Net&amp; System.Drawing

在VB.net中,语法为using wc as WebClient = new WebClient() {

答案 2 :(得分:3)

您可以使用HttpClient并用几行代码异步完成此任务。

public async Task<Bitmap> GetImageFromUrl(string url)
    {
        var httpClient = new HttpClient();
        var stream = await httpClient.GetStreamAsync(url);
        return new Bitmap(stream);
    }

答案 3 :(得分:1)

你可以尝试这个来获取图像

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()

答案 4 :(得分:1)

iTextSharp能够接受Uri:

Image.GetInstance(uri)

答案 5 :(得分:0)

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)