创建图像的缩略图并将其存储在缓存中

MBU*_*MBU 5 c# wpf listbox image

我有一个WPF应用程序,其中包含一个图像列表框.现在我使用BitmapImage和BitmapCacheOption.OnLoad来加载图像.问题在于,当存在大量图像时,由于图像的大小,RAM使用天空火箭.如何创建要在列表框中显示的原件缩略图?它可能必须被缓存,因为我可以在应用程序运行时删除或修改目录中的图像文件.

Bro*_*ass 2

您可以使用以下命令创建像样的拇指位图InterpolationMode.HighQualityBicubic

   Bitmap bitmap = ...
   Bitmap thumbBitmap = new System.Drawing.Bitmap(thumbWidth, thumbHeight);
   using (Graphics g = Graphics.FromImage(thumbBitmap))
   {
      g.InterpolationMode = InterpolationMode.HighQualityBicubic;
      g.DrawImage(bitmap, 0, 0, thumbWidth, thumbHeight);
   }
Run Code Online (Sandbox Code Playgroud)

如果您在后台线程中创建拇指,只需将它们保存到内存流中,然后您可以在BitmapImage请求时懒惰地使用它来创建:

   _ms = new MemoryStream();
   thumbBitmap.Save(_ms, ImageFormat.Png);
   _ms.Position = 0;
   ImageLoaded = true;


    //thumb image property of this class, use in binding  
    public BitmapImage ThumbImage
    {
        get
        {
            if (_thumbImage == null && ImageLoaded)
            {
                BitmapImage bi = new BitmapImage();
                bi.BeginInit();
                bi.StreamSource = _ms;
                bi.EndInit();
                _thumbImage = bi;
            }
            return _thumbImage;
        }
    }
Run Code Online (Sandbox Code Playgroud)