来自 URL 的 VB.Net Imagelist Listview

问题描述

我有一个显示多个 jpg 图像的网站,我想从 URl 加载它们并将它们显示在我的图像列表中。

我能够使用以下代码对我的 SSD 上的图像做到这一点:

Dim count as integer = 0
Dim imgs as ImageList = New ImageList()
imgs.ImageSize = New Size(75,75)

Dim files as String()
files = Directory.GetFiles("C:/image/folger")

ListView.SmallImageList = imgs  

For each x in files
   imgs.Images.Add(Image.FromFile(f))
   ListView.Items.Add("Image Number: " & count,count)
Next

现在我想实现同样的事情,但是从 URL 开始,而不是先将文件下载到我的驱动程序。我使用以下代码完成了 50%:

    //Loading the Image from URL into Memory as Bitmap fuirst
    Dim tClient As WebClient = New WebClient
    Dim timage As Bitmap = Bitmap.FromStream(New MemoryStream(tClient.DownloadData("https://url.to.image/1.jpg"))) 

    //Applying the Bitmap from Memory into the ImageList
    Dim imgs As ImageList = New ImageList()
    imgs.ImageSize = New Size(50,50)
    imgs.Images.Add(timage)

    ListView1.SmallImageList = imgs
    ListView1.Items.Add("Image " & vbCrLf & count.ToString,count)

这很好用,但正如您所看到的,缺少“Loop - For Each”。我不知道如何请求或收集网站上的每张图片。由于所有图像都是“x.jpg”,而 x 总是并且只是一个数字,我想通过网站源代码搜索每个图像,直到没有图像为止。如果有人能帮我解决这个问题,那就太好了。

解决方法

您可以下载照片,直到出现 http 错误 404,这意味着该地址不存在。

Dim pictIndx As Integer = 0
Dim tClient As WebClient = New WebClient
Dim imgs As ImageList = New ImageList()

Try
   While True
       'Download until you get 404
       pictIndx += 1
       Dim tImage As Bitmap = Bitmap.FromStream(New MemoryStream(tClient.DownloadData("https://url.to.image/" & pictIndx & ".jpg"))) 
       'Download the image
       imgs.ImageSize = New Size(50,50)
       imgs.Images.Add(tImage)
       'Add the image to the ListView
       ListView1.SmallImageList = imgs
       ListView1.Items.Add("Image " & vbCrLf & count.ToString,count)

   End While
Catch ex as Exception
 'You downloaded all the photos
End Try

如果这不起作用,请告诉我