C# 如何在c中快速缩略#
无论ImageList和listview中要使用的资源的使用情况如何,我都试图尽可能快地浏览图像,目前我就是这样做的,但速度似乎很慢:C# 如何在c中快速缩略#,c#,thumbnails,performance,C#,Thumbnails,Performance,无论ImageList和listview中要使用的资源的使用情况如何,我都试图尽可能快地浏览图像,目前我就是这样做的,但速度似乎很慢: public Image toThumbs(string file, int width, int height) { image = null; aspectRatio = 1; fullSizeImg = null; try
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导入或其他什么?请帮帮我
编辑:刚刚在这里找到了一个解决方案
它从文件中提取缩略图
没有读取整个文件。当我使用这个时,我能够减少大约40%的时间
出于好奇,您是否在System.Drawing.Bitmap上尝试过GetThumbnailImage方法?它至少值得与您当前的实现进行比较。这似乎是一个显而易见的答案,但您是否尝试过仅使用Image.GetThumbnailImage()
你无法控制结果的质量,但如果速度是你主要关心的问题,你的计算只需几分之一秒。调用
DrawImage
很可能是其中最慢的部分(因为它正在进行缩放)
如果你只需要这个缩略图一次,那么我看这里没有太多的改进空间。如果在同一个图像上多次调用该方法,则应该缓存缩略图。我使用的这种机制似乎非常快
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;
}
希望这能有所帮助。你的缩略图提取能够大大加快速度,这取决于图像中已经嵌入了缩略图 要加快原始版本的速度,您可能会发现:-
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.HighQualityBicubic;
到
可能会有帮助。您是否做过任何分析以查看时间花在了哪里?例如,Visual Studio 2010有一个内置的探查器。我在代码中添加了时间戳,似乎GetThumbnailImage速度较慢。您可以异步创建它们,这样gui就不会在其上“冻结”。但我需要用白色填充图像的透明度,所以我仍然需要图形类。嗯。。你是对的,因为我只对每个图像缩略一次,所以似乎没有其他方法。如果你每次启动应用程序时都这样做,那么你仍然可以通过将缩略图存储在文件中来缓存它们。图像重采样,特别是对大图像的重采样非常昂贵。但是如果图像被编辑了呢?由于缓存是较旧的版本,我如何确定需要重建thumb?通常,这是通过比较缩略图和图像的上次修改日期来完成的。但是是的,缓存总是容易受到数据更改的影响。我认为这是一个误导性的答案,因为我处理的是文件而不是url。这是使用URI,它可以是文件的路径。
graphics.InterpolationMode = System.Drawing.Drawing2D.InterpolationMode.Low;