36

我正在使用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)
4

6 回答 6

75

您可以使用 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)
于 2012-08-03T18:59:58.947 回答
19

其他答案也是正确的,但是看到 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.IO, System.Net&System.Drawing

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

于 2016-01-20T11:04:58.327 回答
3

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

public async Task<Bitmap> GetImageFromUrl(string url)
    {
        var httpClient = new HttpClient();
        var stream = await httpClient.GetStreamAsync(url);
        return new Bitmap(stream);
    }
于 2020-01-19T05:37:10.757 回答
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()
于 2012-08-03T19:00:00.550 回答
1

iTextSharp 能够接受 Uri 的:

Image.GetInstance(uri)
于 2012-08-04T04:33:22.493 回答
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)
于 2012-08-03T19:01:50.503 回答