vb.net 从 url 保存图像
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/9689105/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
save images from url
提问by John
Is it possible to save images using Visual Basic 2008
from URL to my PC?
是否可以使用Visual Basic 2008
URL将图像保存到我的 PC?
For example: From www.domain.com/image.jpg
to C:\folder\image.jpg
例如:从www.domain.com/image.jpg
到C:\folder\image.jpg
P.S: I need simpliest example of the code, then I will edit is as I need.
PS:我需要最简单的代码示例,然后我会根据需要进行编辑。
Thanks.
谢谢。
Update : I want to know when the code have finished downloading of the image.
更新:我想知道代码何时完成图像的下载。
回答by UnhandledExcepSean
This is the simplest way I know.
这是我知道的最简单的方法。
Dim Client as new WebClient
Client.DownloadFile(Source, Destination)
Client.Dispose
This is superior to using the My.Computer.Network.DownloadFile method per Microsoft's documentation
这优于使用 Microsoft文档中的 My.Computer.Network.DownloadFile 方法
"The DownloadFile method does not send optional HTTP headers. Some servers may return 500 (Internal Server Error) if the optional user agent header is missing. To send optional headers, you must construct a request using the WebClient class."
“DownloadFile 方法不发送可选的 HTTP 标头。如果缺少可选的用户代理标头,某些服务器可能会返回 500(内部服务器错误)。要发送可选的标头,您必须使用 WebClient 类构造一个请求。”
回答by user3102516
There's a simpler way:
有一个更简单的方法:
My.Computer.Network.DownloadFile(Source, Desination)
回答by Ad Kahn
Here what i came up with.
这是我想出的。
Public Function getImgFrmUrl(ByVal url As String, ByVal Optional ImageName As String = "", ByVal Optional DstntnPath As String = "c:\") As String
Dim imgPath = DstntnPath & "\"
Dim name = IIf(ImageName.Length = 0, Guid.NewGuid.ToString, ImageName)
Dim fileExt = Path.GetExtension(url)
Using webClient As WebClient = New WebClient
Const _Tls12 As SslProtocols = CType(&HC00, SslProtocols)
Const Tls12 As SecurityProtocolType = CType(_Tls12, SecurityProtocolType)
ServicePointManager.SecurityProtocol = Tls12
Dim data As Byte() = webClient.DownloadData(url)
If File.Exists(imgPath + name & fileExt) Then File.Delete(imgPath + name & fileExt)
Using mem = New MemoryStream(data)
Using yourImage = Image.FromStream(mem)
If fileExt.ToLower Is ".png" Then
yourImage.Save(imgPath + name & fileExt, ImageFormat.Png)
Else
yourImage.Save(imgPath + name & fileExt, ImageFormat.Jpeg)
End If
End Using
End Using
End Using
Return imgPath & name & fileExt
End Function