如何将图片URL转换为System.Drawing.Image

37

我正在使用 VB.Net,有一个图像的URL,例如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个回答

78
你可以使用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)

如果您担心图像不存在,您会将MemoryStream部分放在using语句中吗? - Jason
如果您能提供C#路由的ASP.Net MVC和ASP.Net Core解决方案,我一定会非常支持并点赞。因为ASP.Net Core无法使用WebClient。 - LatentDenis

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.IOSystem.NetSystem.Drawing

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


4
您可以使用HttpClient,并用几行代码异步完成此任务。
public async Task<Bitmap> GetImageFromUrl(string url)
    {
        var httpClient = new HttpClient();
        var stream = await httpClient.GetStreamAsync(url);
        return new Bitmap(stream);
    }

请考虑为您的答案添加一些说明或细节。尽管它可能回答了问题,但只是添加一份代码作为答案,并不能帮助问题提出者或未来的社区成员理解问题或提出的解决方案。 - Maxim

2

iTextSharp能够接受Uri:

Image.GetInstance(uri)

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

你能告诉我如何在 Response.ContentType = "image/png" 的页面上实现相同的功能吗?非常感谢。 - Mina Gabriel
我可以用同样的方法来做,就像处理任何图像一样,response.GetResponseStream() 应该能够正常工作。 - Guilherme de Jesus Santos

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)

其实,我更喜欢他的 ^ 我只是急着想要第一个。 - blang32
不需要保存文件(可以使用内存流进行操作),只需添加可能出现的问题(例如,您在无法编写指定路径的 Web 应用程序中)。 - Gian Paolo

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接