此代码非常适合生成缩略图,但是当给定非常大(100MB +)的TIFF文件时,它会抛出OutOfMemoryExceptions。当我在同一台机器上的Paint.NET中手动完成时,它工作正常。如何改进此代码以停止抛出非常大的文件?
在这种情况下,我在一台8GB RAM的机器上加载721MB TIF。任务管理器显示2GB已使用,因此有些东西阻止使用所有内存。特别是当我加载Image以计算原始大小时它会抛出。是什么给了什么?
/// <summary>Creates a thumbnail of a given image.</summary>
/// <param name="inFile">Fully qualified path to file to create a thumbnail of</param>
/// <param name="outFile">Fully qualified path to created thumbnail</param>
/// <param name="x">Width of thumbnail</param>
/// <returns>flag; result = is success</returns>
public static bool CreateThumbnail(string inFile, string outFile, int x)
{
// Mathematically determine Y dimension
int y;
using (Image img = Image.FromFile(inFile)) // Exception thrown
y = (int)((double)img.Height * ((double)x / (double)img.Width));
// Make thumbnail
using (Bitmap bmp = new Bitmap(inFile))
using (Bitmap thumb = new Bitmap((Image)bmp, new Size(x, y)))
using (Graphics g = Graphics.FromImage(thumb)) {
g.SmoothingMode = SmoothingMode.HighQuality;
g.InterpolationMode = InterpolationMode.High;
g.CompositingQuality = CompositingQuality.HighQuality;
ImageCodecInfo codec = ImageCodecInfo.GetImageEncoders()[1];
EncoderParameters ep2 = new EncoderParameters(1);
ep2.Param[0] = new EncoderParameter(Encoder.Quality, 100L);
g.DrawImage(bmp, new Rectangle(0,0,thumb.Width, thumb.Height));
try {
thumb.Save(outFile, codec, ep2);
return true; }
catch { return false; }
}
}
答案 0 :(得分:1)
我的猜测是,您将其作为32位应用程序运行。这将你的应用内存使用限制在理论上的2 GB,实际上更像是1.5 GB。
答案 1 :(得分:0)
您是否尝试过使用FastImageGDIPlus。它对我有用 - 但我从未尝试加载721 MB文件。