我正在检查图像的宽度和高度,并尝试删除所有不满足if要求的图像。如果需求有效(从12-> 1开始),并且在这种情况下我不能使用f.delete,因为它抛出错误“另一个程序正在使用f;无法打开image10.jpg”(12和11不能满足“如果”要求,则为10。)
如何删除满足If要求的图像?
Dim s As New DirectoryInfo("C:\Users\*\source\repos\CinemaSpider\CinemaSpider\bin\Debug")
Dim files As FileInfo() = s.GetFiles("*.jpg")
For Each f As FileInfo In files
Dim bmp As New Bitmap(f.FullName)
If bmp.Width.ToString() < 182 Or bmp.Height.ToString() < 268 Then
f.Delete()
End If
答案 0 :(得分:1)
您必须先删除对图像的引用,然后再尝试删除它。最好的方法是使用using
:
Dim s As New DirectoryInfo("C:\Users\*\source\repos\CinemaSpider\CinemaSpider\bin\Debug")
Dim files As FileInfo() = s.GetFiles("*.jpg")
For Each f As FileInfo In files
Dim DoDelete as Boolean= false
Using image1 As Image = Image.FromFile(f.FullName)
If image1.Width < 182 OrElse image1.Height < 268 Then
DoDelete = True
End If
End Using
if DoDelete Then f.Delete()
Next
答案 1 :(得分:1)
使用Microsoft Shell Controls And Automation
COM库提供的Shell扩展的方法稍有不同。
您无需加载位图并进行处理就可以收集所需的信息。这些是由Shell提供的。
All Windows Properties related to Shell Object types。
要使用Shell32命名空间,您需要在项目中向该类型库添加引用:
Project -> References -> COM -> Type Library -> Microsoft Shell Controls And Automation
Imports Shell32
Dim imageFolder As String = "[Insert Your Path]"
Dim shell As New Shell()
Dim items As FolderItems = shell.NameSpace(imageFolder).Items
For Each item As FolderItem2 In items
If item.ExtendedProperty("Type").ToString().Contains("JPEG") Then
If CInt(item.ExtendedProperty("System.Image.HorizontalSize")) < 187 OrElse
CInt(item.ExtendedProperty("System.Image.VerticalSize")) < 268 Then
File.Delete(item.Path)
End If
End If
Next
Marshal.ReleaseComObject(items)
Marshal.FinalReleaseComObject(shell)
Marshal.CleanupUnusedObjectsInCurrentContext()