我得到Memory Out of Range
例外,用于比较两个jpeg文件的静态方法。为静态方法获取内存超出范围例外
我能不过来识别我的代码部分使用分析器占用了大部分的内存,我不能释放内存,即使我尝试GC.Collect的()
public static bool IsDuplicate(string newFile, string pathDestination)
{
string[] destinationFiles = Directory.GetFiles(pathDestination); // 1100 jpeg files.
foreach (var file in destinationFiles)
{
if (CompareImageFiles(newFile, file))
return true;
}
return false;
}
//1100 jpeg files (pathFile2) being compared with one jpeg file (pathFile1)
public static bool CompareImageFiles(string pathFile1, string pathFile2)
{
// Memory consumption around 1 GB by ms
MemoryStream ms = new MemoryStream();
// Memory consumption around 2.7 GB by img1
System.Drawing.Image img1 = System.Drawing.Image.FromFile(pathFile1);
// Memory consumption around 3 GB by img2
System.Drawing.Image img2 = System.Drawing.Image.FromFile(pathFile2);
if (!(img1.Height == img2.Height && img1.Width == img2.Width))
{
return false; // Dimensions mismatch
}
else
{
img1.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
string image1 = Convert.ToBase64String(ms.ToArray());
img2.Save(ms, System.Drawing.Imaging.ImageFormat.Jpeg);
string image2 = Convert.ToBase64String(ms.ToArray());
if (image1.Equals(image2))
{
// This didn't work
//ms = null; img1 = null; img2 = null; image1 = null; image2 = null;
return true;
}
else
{
// This didn't work
//ms = null; img1 = null; img2 = null; image1 = null; image2 = null;
return false;
}
}
}
小背景:是的,我明白这不是比较图像文件的最佳方法(我第一次尝试处理图像文件)。我已经开始了此任务的新优化版本(进行中)。
但是,由于该解决方案自过去几个月开始运作并且最近开始破产。所以,在我将这种方法归档之前,至少我想解决这个问题,这给了我一个很好的学习。
如何第一比较文件 - 大小来处理处理?然后你散列这些文件并比较散列 - 如果它们不同,它们在内部也是不同的。不需要这个图像的东西?那么你应该做的更快,更多的资源友好。 –
您的应用程序正在泄漏。任何实现Dispose方法的东西都必须在你完成后处理掉。 – Plutonix
试试这个:https://stackoverflow.com/a/16318177/7505395 –