循环浏览包含图像的文件夹,调整图像大小并放在新文件夹中

时间:2014-11-06 22:17:48

标签: c#

我有以下代码,可以简单地抓取特定图像并提供固定大小,而不管原始大小。这是欲望行动。

问题是,我必须一次从源文件夹1中选择每个图像。

我需要遍历Source文件夹,调整每个图像的大小,然后将图像保存在目标文件夹中。我熟悉循环文件,但不一定是图像。

代码:

class Program
{
    public static Image ScaleImage(Image image, int maxWidth, int maxHeight)
    {
        var newImage = new Bitmap(maxWidth, maxHeight);
        using (Graphics graphics = Graphics.FromImage(newImage))
        {
            graphics.CompositingQuality =
           System.Drawing.Drawing2D.CompositingQuality.HighQuality;
            graphics.InterpolationMode =
            System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
            graphics.SmoothingMode =
            System.Drawing.Drawing2D.SmoothingMode.HighQuality;
            graphics.DrawImage(image, 0, 0, maxWidth, maxHeight);
        }

        return newImage;

    }

    static void Main(string[] args)
    {
        var image = Image.FromFile(@"C:\Source\original_image.jpg");
        var newImage = ScaleImage(image, 150, 150);
        newImage.Save(@"C:\Dest\resized_image.png", ImageFormat.Png);
    }
}

1 个答案:

答案 0 :(得分:4)

var files = new DirectoryInfo(@"C:\Source\")
            .GetFiles()
            .Where(f => f.IsImage());

foreach (var file in files)
{
      using (var image = Image.FromFile(file.FullName))
      {
            using (var newImage = ScaleImage(image, 150, 150))
            {
                try
                {
                    var newImageName = Path.Combine(@"C:\Dest\", Path.GetFileNameWithoutExtension(file.Name) + "_resized" + file.Extension);
                    newImage.Save(newImageName, ImageFormat.Jpeg);
                }
                catch
                {
                    continue;
                }
            }
        }
    }
}


public static class Extensions
{
    public static bool IsImage(this FileInfo file)
    {
        var allowedExtensions = new[] {".jpg", ".png", ".gif", ".jpeg"};
        return allowedExtensions.Contains(file.Extension.ToLower());
    }
}