簡體   English   中英

如何從硬盤獲取圖像,調整圖像大小並將其添加到列表中 <image> 快速?

[英]How can i get images from the hard disk resize the images and add them to a list<image> fast?

我現在在做

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<Image> imageslist所有分辨率為100,100的圖像,並且這些圖像現在是24位深度,我是否也應該嘗試更改它,否則24位就可以了?

我有兩個改進:

  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的情況下運行代碼)之后,您才能確保它可以提高性能。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM