您可以使用WebClient.DownloadFileTaskAsync 方法下载位图文件(如果您需要存储这些文件并最终只下载位图的更新),然后从文件中加载图像:
(要使用这种异步方法,您的代码需要包含在 async 方法/事件处理程序中)
Dim imageURL As String = "https://storage.googleapis.com/ygoprodeck.com/pics/27551.jpg"
Dim imageURI As Uri = New Uri(imageURL)
Dim bitmapFile As String = Path.Combine(Application.StartupPath, $"images\{imageURI.Segments.Last()}")
Using client As WebClient = New WebClient()
Await client.DownloadFileTaskAsync(imageURI, bitmapFile)
PictureBox1.Image?.Dispose()
PictureBox1.Load(bitmapFile)
End Using
我的建议是在数据库中注册Bitmap的文件名;仅文件名,而不是完整路径:应在应用程序第一次下载图像时确定图像的位置,并且可能会更改(或者用户可能出于任何原因更改它)。如果需要重新定位镜像,只需更新存储路径即可。
该信息也可以存储在数据库中。
添加一个布尔字段[Downloaded],以在下载图像后设置为True(以过滤还没有关联位图的记录)。
如果您不想或无法下载位图,可以使用PictureBox.LoadAsync 方法(或同步PictureBox.Load 方法)让控件为您完成工作:
Dim imageURL As String = "https://storage.googleapis.com/ygoprodeck.com/pics/27551.jpg"
PictureBox1.Image?.Dispose()
PictureBox1.LoadAsync(imageURL)
或者使用WebClient.DownloadDataTaskAsync()方法将图片数据下载为Byte数组,从MemoryStream生成新的Bitmap。位图不会保存在光盘上:
Dim imageURL As String = "https://storage.googleapis.com/ygoprodeck.com/pics/27551.jpg"
Dim client As WebClient = New WebClient()
Dim ms As MemoryStream = New MemoryStream(
Await client.DownloadDataTaskAsync(New Uri(imageURL))
)
Using image As Image = Image.FromStream(ms)
PictureBox1.Image?.Dispose()
PictureBox1.Image = DirectCast(image.Clone(), Image)
End Using
ms.Dispose()
client.Dispose()