【问题标题】:Show an Image in a PictureBox using the URL from an Access database使用 Access 数据库中的 URL 在 PictureBox 中显示图像
【发布时间】:2019-04-06 00:42:27
【问题描述】:

我有一个 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

【问题讨论】:

    标签: vb.net winforms ms-access


    【解决方案1】:

    您可以使用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()
    

    【讨论】:

    • 好吧,我很高兴它有帮助:)
    • 在您的数据库中添加一列以供下载,以便您的程序知道在哪里查找图片(区域设置存储或网络)该网站只希望您下载一次图像,然后将其存储在本地。
    猜你喜欢
    • 2019-01-20
    • 2013-08-28
    • 2021-01-15
    • 1970-01-01
    • 2012-09-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多