[英]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.