我尝试比较2张图片。为此我使用2个PreentScreens一个接一个地做(这是理想的)。当我使用像素比较来比较这个屏幕时:
public static CompareResult Compare(Bitmap bmp1, Bitmap bmp2)
{
CompareResult cr = CompareResult.ciCompareOk;
if (bmp1.Size != bmp2.Size)
{
cr = CompareResult.ciSizeMismatch;
}
else
{
for (int x = 0; x < bmp1.Width
&& cr == CompareResult.ciCompareOk; x++)
{
for (int y = 0; y < bmp1.Height
&& cr == CompareResult.ciCompareOk; y++)
{
if (bmp1.GetPixel(x, y) != bmp2.GetPixel(x, y))
cr = CompareResult.ciPixelMismatch;
}
}
}
return cr;
}
我得到的结果是正确的 - 比较是相同的,但是需要花费很多时间,当我尝试哈希这个位图并比较它的值时 - 我得到了错误的结果。当我将图像与自身进行比较时 - 一切正常。有什么不对?这是哈希比较的代码:
public enum CompareResult
{
ciCompareOk,
ciPixelMismatch,
ciSizeMismatch
};
public static CompareResult Compare(Bitmap bmp1, Bitmap bmp2)
{
CompareResult cr = CompareResult.ciCompareOk;
//Test to see if we have the same size of image
if (bmp1.Size != bmp2.Size)
{
cr = CompareResult.ciSizeMismatch;
}
else
{
//Convert each image to a byte array
System.Drawing.ImageConverter ic =
new System.Drawing.ImageConverter();
byte[] btImage1 = new byte[1];
btImage1 = (byte[])ic.ConvertTo(bmp1, btImage1.GetType());
byte[] btImage2 = new byte[1];
btImage2 = (byte[])ic.ConvertTo(bmp2, btImage2.GetType());
//Compute a hash for each image
SHA256Managed shaM = new SHA256Managed();
byte[] hash1 = shaM.ComputeHash(btImage1);
byte[] hash2 = shaM.ComputeHash(btImage2);
//Compare the hash values
for (int i = 0; i < hash1.Length && i < hash2.Length
&& cr == CompareResult.ciCompareOk; i++)
{
if (hash1[i] != hash2[i])
cr = CompareResult.ciPixelMismatch;
}
}
return cr;
}
答案 0 :(得分:1)
包含示例代码的How to compare Image objects with C# .NET?的可能重复。
另一个有用的链接是Dominic Green的this博客文章。代码有点小,使用Base64散列而不是SHA256散列。这明显更快,但你应该知道比较图像不是轻微的操作。
但回到问题本身,你有多确定两张图片都是平等的?是否可能两个图像之间可能存在细微差别?您的鼠标光标移动,时钟显示更新,...