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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 16:00:23  来源:igfitidea点击:

save images from url

vb.netvisual-studio-2008

提问by John

Is it possible to save images using Visual Basic 2008from URL to my PC?

是否可以使用Visual Basic 2008URL将图像保存到我的 PC?

For example: From www.domain.com/image.jpgto C:\folder\image.jpg

例如:从www.domain.com/image.jpgC:\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