【问题标题】:How can i get images from the hard disk resize the images and add them to a list<image> fast?如何从硬盘中获取图像调整图像大小并将它们快速添加到列表<图像>?
【发布时间】:2016-12-25 22:26:19
【问题描述】:

我现在在做

imageslist = new List<Image>();
            foreach (string myFile in
                      Directory.GetFiles(dir, "*.bmp", SearchOption.AllDirectories))
            {

                Bitmap bmp = new Bitmap(myFile);
                imageslist.Add(bmp);
            }

但是foreach 很慢。 我有这种方法来调整图像的大小,然后再将它们添加到列表中

public static Bitmap ResizeImage(Image image, int width, int height)
        {
            var destRect = new Rectangle(0, 0, width, height);
            var destImage = new Bitmap(width, height);

            destImage.SetResolution(image.HorizontalResolution, image.VerticalResolution);

            using (var graphics = Graphics.FromImage(destImage))
            {
                graphics.CompositingMode = CompositingMode.SourceCopy;
                graphics.CompositingQuality = CompositingQuality.HighQuality;
                graphics.InterpolationMode = InterpolationMode.HighQualityBicubic;
                graphics.SmoothingMode = SmoothingMode.HighQuality;
                graphics.PixelOffsetMode = PixelOffsetMode.HighQuality;

                using (var wrapMode = new ImageAttributes())
                {
                    wrapMode.SetWrapMode(WrapMode.TileFlipXY);
                    graphics.DrawImage(image, destRect, 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, wrapMode);
                }
            }

            return destImage;
        }

最后我想在List&lt;Image&gt; imageslist 中拥有分辨率为 100,100 的所有图像,并且图像现在是 24 位深度,我应该尝试更改它还是 24 位可以?

【问题讨论】:

    标签: c# .net image winforms performance


    【解决方案1】:

    我有两个改进:

    1. 使用 Directory.EnumerateFiles 而不是 Directory.GetFiles,您不必等到所有结果都返回,它会被懒惰地评估
    2. 并行运行调整大小(在下面的示例中,使用 AsParallel 扩展方法)

     

    var imageslist = Directory.EnumerateFiles(dir, "*.bmp", SearchOption.AllDirectories)
        .AsParallel()
        .Select(path => new Bitmap(path))
        .Select(bmp => ResizeImage(bmp, 100, 100))
        .ToList();
    

    请记住验证并行解决方案的速度,因为只有在将其与非并行解决方案进行比较之后(在没有 AsParallel 的情况下运行代码),您才能确定它在您的情况下会提高性能。

    【讨论】:

      猜你喜欢
      • 2016-08-18
      • 1970-01-01
      • 2011-07-19
      • 1970-01-01
      • 2014-07-08
      • 1970-01-01
      • 1970-01-01
      • 2010-12-29
      • 2021-06-05
      相关资源
      最近更新 更多