如何在c#中更快地缩略图

我试图尽可能快地缩略图像,无论在我的ImageList和listview中使用的资源的使用情况如何,这是我现在正在做的但它看起来很慢:

public Image toThumbs(string file, int width, int height) { image = null; aspectRatio = 1; fullSizeImg = null; try { fullSizeImg = Image.FromFile(file); float w = fullSizeImg.Width; float h = fullSizeImg.Height; aspectRatio = w / h; int xp = width; int yp = height; if (fullSizeImg.Width > width && fullSizeImg.Height > height) { if ((float)xp / yp > aspectRatio) { xp = (int)(yp * aspectRatio); } else { yp = (int)(xp / aspectRatio); } } else if (fullSizeImg.Width != 0 && fullSizeImg.Height != 0) { xp = fullSizeImg.Width; yp = fullSizeImg.Height; } image = new Bitmap(width, height); graphics = Graphics.FromImage(image); graphics.FillRectangle(Brushes.White, ((width - xp) / 2), (height - yp), xp, yp); graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; graphics.DrawImage(fullSizeImg, new Rectangle(((width - xp) / 2), (height - yp), xp, yp)); graphics.Dispose(); fullSizeImg.Dispose(); } catch (Exception) { image = null; } return image; } 

我不确定计算是否会减慢缩略图或者正在使用的类本身可能很慢,如果是这种情况那么其他替代方案可能会使用可能是不同的计算或我需要导入其他类或是否有可以使用的第三方库或我需要进行dll导入或其他什么? 请帮我。

编辑:刚刚在这里找到了解决方案http://www.vbforums.com/showthread.php?t=342386它从文件中提取缩略图而不读取整个文件。 当我使用它时,我能够减少大约40%的时间。

你的计算只需几分之一秒。 对DrawImage的调用很可能是最慢的部分(因为那个正在进行缩放)。

如果您只需要一次缩略图,那么我在这里看不到太大的改进空间。 如果您在同一图像上多次调用该方法,则应缓存缩略图。

出于好奇,您是否在System.Drawing.Bitmap上尝试了GetThumbnailImage方法? 它至少值得与您当前的实现进行比较。

我使用这种机制似乎非常快。

  BitmapFrame bi = BitmapFrame.Create(new Uri(value.ToString()), BitmapCreateOptions.DelayCreation, BitmapCacheOption.OnDemand); // If this is a photo there should be a thumbnail image, this is VERY fast if (bi.Thumbnail != null) { return bi.Thumbnail; } else { // No thumbnail so make our own (Not so fast) BitmapImage bi2 = new BitmapImage(); bi2.BeginInit(); bi2.DecodePixelWidth = 100; bi2.CacheOption = BitmapCacheOption.OnLoad; bi2.UriSource = new Uri(value.ToString()); bi2.EndInit(); return bi2; } 

希望这可以帮助。

这似乎是一个明显的答案,但你尝试过使用Image.GetThumbnailImage()吗?

你没有尽可能多地控制结果的质量,但速度是你的主要关注点吗?

您的缩略图提取可以让您获得更快的速度依赖于已嵌入缩略图的图像。

为了加快原始速度,您可能会发现变化: –

 graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic; 

 graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low; 

可能有帮助。