我正在使用VB.Net
,我有图片的网址,例如http://localhost/image.gif
我需要从该文件创建System.Drawing.Image对象。
Notice将此保存到文件然后打开它不是我的选择之一我也在用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.IO
,System.Net
和System.Drawing
在VB.net中,语法为using wc as WebClient = new WebClient() {
等
您可以尝试获得图像
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)
您可以使用HttpClient并用几行代码异步完成此任务。
public async Task<Bitmap> GetImageFromUrl(string url)
{
var httpClient = new HttpClient();
var stream = await httpClient.GetStreamAsync(url);
return new Bitmap(stream);
}