[英]How to thumbnail faster in 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;
可能有帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.