VB.NET 2022中如何让ListBox仅显示图片文件
问题:如何让ListBox仅列出图片文件?
我用以下代码将文件夹中的文件名加载到ListBox中:
ListBox1.Items.Clear() If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK And FolderBrowserDialog1.SelectedPath = Folder1Path.Text Or FolderBrowserDialog1.SelectedPath = Folder2Path.Text Or FolderBrowserDialog1.SelectedPath = Folder3Path.Text Then MsgBox("Unable to open a same folder") Else SourceFolderPath.Text = FolderBrowserDialog1.SelectedPath Dim filenames As String() = IO.Directory.GetFiles(FolderBrowserDialog1.SelectedPath) If filenames.Length > 0 Then For Each names As String In filenames Dim justname As String = IO.Path.GetFileName(names) ListBox1.Items.Add(justname) Next End If End If
目前ListBox显示结果包含非图片文件:
456.pub 1.img gmoier.img
我尝试在filenames.Length > 0后添加filenames.OfType(Of Image)但出现错误,该如何解决?
解决方案
方法1:按文件扩展名筛选
直接通过常见图片扩展名判断,代码修改如下:
ListBox1.Items.Clear() If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK And FolderBrowserDialog1.SelectedPath = Folder1Path.Text Or FolderBrowserDialog1.SelectedPath = Folder2Path.Text Or FolderBrowserDialog1.SelectedPath = Folder3Path.Text Then MsgBox("Unable to open a same folder") Else SourceFolderPath.Text = FolderBrowserDialog1.SelectedPath ' 定义需筛选的图片扩展名集合,可按需增减 Dim imageExtensions As New HashSet(Of String) From {".jpg", ".jpeg", ".png", ".gif", ".bmp", ".img"} Dim filenames As String() = IO.Directory.GetFiles(FolderBrowserDialog1.SelectedPath) If filenames.Length > 0 Then For Each names As String In filenames Dim ext As String = IO.Path.GetExtension(names).ToLower() ' 匹配扩展名则添加到ListBox If imageExtensions.Contains(ext) Then Dim justname As String = IO.Path.GetFileName(names) ListBox1.Items.Add(justname) End If Next End If End If
说明
- 用
HashSet存储扩展名是为了提升查找效率,也可替换为普通数组 ToLower()避免大小写匹配问题,比如.JPG和.jpg都能被识别- 可根据需求添加其他图片格式,比如
.webp、.tiff等
方法2:验证文件是否为有效图片(避免扩展名伪装)
如果需要确保文件是真正可识别的图片(而非改了扩展名的非图片文件),可通过加载文件验证:
ListBox1.Items.Clear() If FolderBrowserDialog1.ShowDialog = Windows.Forms.DialogResult.OK And FolderBrowserDialog1.SelectedPath = Folder1Path.Text Or FolderBrowserDialog1.SelectedPath = Folder2Path.Text Or FolderBrowserDialog1.SelectedPath = Folder3Path.Text Then MsgBox("Unable to open a same folder") Else SourceFolderPath.Text = FolderBrowserDialog1.SelectedPath Dim filenames As String() = IO.Directory.GetFiles(FolderBrowserDialog1.SelectedPath) If filenames.Length > 0 Then For Each names As String In filenames Try ' 尝试加载图片,成功则判定为有效图片 Using img As Image = Image.FromFile(names) Dim justname As String = IO.Path.GetFileName(names) ListBox1.Items.Add(justname) End Using Catch ex As Exception ' 加载失败则跳过该文件 End Try Next End If End If
说明
- 用
Try-Catch捕获加载失败的情况,过滤无效图片 Using语句确保图片资源被及时释放,避免内存泄漏- 该方法准确性更高,但速度比扩展名筛选慢,适合对精度要求高的场景
为什么OfType(Of Image)会报错?
filenames是字符串数组,存储的是文件路径字符串,并非Image对象。OfType(Of Image)只能从集合中筛选指定类型的元素,自然无法从字符串集合中得到Image类型,因此会报错。
内容的提问来源于stack exchange,提问作者Irfan Azhari
相关产品推荐
相关产品推荐

