如何将图像URL转换为system.drawing.image

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

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

其他答案也是正确的,但是看到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() { etc

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

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

iTextSharp能够接受Uri:

 Image.GetInstance(uri) 
 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)