调整多个图像的大小并将它们保存到单独的文件夹中

Resizing multiple images and saving them to a separate folder

我需要调整和压缩存储在文件夹中的 200 张图像。 我正在使用从另一个问题获得的代码将这些图像放入列表中:

Dim dir = New IO.DirectoryInfo("C:\Users\Charbel\Desktop\Images")
Dim images = dir.GetFiles("*.jpg", IO.SearchOption.AllDirectories).ToList
Dim pictures As New List(Of PictureBox)
For Each img In images
    Dim picture As New PictureBox
    picture.Image = Image.FromFile(img.FullName)
    pictures.Add(picture)
Next

现在,我需要将每个图像压缩并缩小到 (500x374),然后将它们保存在我电脑上的另一个文件夹中。

那么,首先让我指出关于您的代码的几点:

  • PictureBox 在这里没有任何作用。您不应该创建 PictureBox 来使用图像。
  • 永远记得处置 Image 对象(例如,将其包装在 Using 块中),这样您就不会 运行 出现内存问题。
  • 与 C# 不同,VB.NET 不需要转义 \ 字符,因此,您可以这样写路径 "C:\Users...".

现在,要调整图像大小,您只需创建 Bitmap class with the constructor that takes an image and a size argument: Bitmap(Image, Size) or Bitmap(Image, Int32, Int32).

的实例即可

这里:

Dim sourcePath As String = "C:\Users\Charbel\Desktop\Images"
Dim outputPath As String = "C:\Users\Charbel\Desktop\Images\Resized"

IO.Directory.CreateDirectory(outputPath)

Dim dir = New IO.DirectoryInfo(sourcePath)
Dim files As IO.FileInfo() = dir.GetFiles("*.jpg", IO.SearchOption.AllDirectories)
For Each fInfo In files
    Using img As Bitmap = Image.FromFile(fInfo.FullName)
        Using resizedImg As New Bitmap(img, 500, 374)
            resizedImg.Save(IO.Path.Combine(outputPath, fInfo.Name),
                            Imaging.ImageFormat.Jpeg)
        End Using
    End Using
Next