使用Access数据库中的URL在PictureBox中显示图像

时间:2019-04-06 00:42:27

标签: vb.net winforms ms-access

我有一个Access数据库,其中包含一个纸牌游戏的卡片及其图片。我数据库中的一列包含这些卡片图像的网址。
但是,我正在努力在PictureBox中显示URL中的图像。

我尝试使用HttpClient类下载它,但是出现了太多错误,因此下面的代码没有任何错误,但仍然无法正常工作:

' adds an image to a PictureBox
PictureBox1.Image = Image.FromFile(dataSet.Tables("YGO cards").Rows(0).Item(8)) 

这会产生一个错误:

  

对象引用未设置为对象的实例。

您知道使用URL显示图像的方法吗?
成千上万个具有不同URL的卡。

以下是其中的两个示例:
https://storage.googleapis.com/ygoprodeck.com/pics/27551.jpg
https://storage.googleapis.com/ygoprodeck.com/pics/41777.jpg

1 个答案:

答案 0 :(得分:0)

您可以使用WebClient.DownloadFileTaskAsync方法下载位图文件(如果需要存储tham,最终仅下载位图的更新),然后从文件中加载图像:
(要使用此异步方法,您的代码必须包含在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

我的建议是在数据库中注册位图的文件名;仅文件名,而不是完整路径:应在应用程序首次下载图像时确定图像的位置,并且该图像可能会更改(或者用户可能出于任何原因更改它)。如果需要重新定位图像,则只需更新存储路径。
该信息也可以存储在数据库中。

添加一个布尔字段[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()