如何区分2张图像并将其保存到图像中

我的意思是标题是我有2张图片 – 每张图片来自不同的时间(来自屏幕截图)我希望得到两者之间的差异使所有相同的部分透明,将差异发送给客户并放置它在他拥有的图像之上

不要担心发送部分 – 我已经涵盖了这一点。 我需要帮助的是如何获得差异,将其保存到图像/流/字节数组并将其合并到一个图像。

您创建并填充目标Bitmap

如果性能太差,请尝试使用LockBits 。 使用库应该更快。

这是一段快速的代码; 你传入两个BitmapsColor应该涂上差异,例如Color.RedColor.Transparent

如果Bitmap Size不匹配,则返回差值Bitmap或null。

 public Bitmap getDifferencBitmap(Bitmap bmp1, Bitmap bmp2, Color diffColor) { Size s1 = bmp1.Size; Size s2 = bmp2.Size; if (s1 != s2) return null; Bitmap bmp3 = new Bitmap(s1.Width, s1.Height); for (int y = 0; y < s1.Height; y++) for (int x = 0; x < s1.Width; x++) { Color c1 = bmp1.GetPixel(x, y); Color c2 = bmp2.GetPixel(x, y); if (c1 == c2) bmp3.SetPixel(x, y, c1); else bmp3.SetPixel(x, y, diffColor); } return bmp3; } 

你可以这样称呼它:

 Bitmap bmp1 = new Bitmap(filepath1); Bitmap bmp2 = new Bitmap(filepath2); Bitmap bmp3 = getDifferencBitmap(bmp1, bmp2, Color.Transparent); bmp3.Save(filepath3, System.Drawing.Imaging.ImageFormat.Png); bmp1.Dispose(); bmp2.Dispose(); bmp3.Dispose(); 

确保在完成Bitmaps丢弃Bitmaps

当然,您可以轻松地更改逻辑以制作相同的零件透明和不相同的零件。但我认为您确实想要显示差异。

这是一篇包含LockBits版本代码的post; 你只需要将内循环的代码更改为:

  for (int x = 0; x < s1.Width; x++) { int index1 = y * bmp1Data.Stride + x * bpp1; int index2 = y * bmp2Data.Stride + x * bpp2; int index3 = y * bmp3Data.Stride + x * bpp3; Color c1, c2; if (bpp1 == 4) c1 = Color.FromArgb(data1[index1 + 3], data1[index1 + 2], data1[index1 + 1], data1[index1 + 0]); else c1 = Color.FromArgb(255, data1[index1 + 2], data1[index1 + 1], data1[index1 + 0]); if (bpp1 == 4) c2 = Color.FromArgb(data2[index2 + 3], data2[index2 + 2], data2[index2 + 1], data2[index2 + 0]); else c2 = Color.FromArgb(255, data2[index2 + 2], data2[index2 + 1], data2[index2 + 0]); Color putColor = (c1 == c2 ? c1 : diffColor); data3[index3 + 0] = putColor.B; data3[index3 + 1] = putColor.G; data3[index3 + 2] = putColor.R; data3[index3 + 3] = putColor.A; } 

这是一种方法,您可以检查两个图像并比较像素

 public void matchimage(System.Drawing.Bitmap img1, System.Drawing.Bitmap img2) { string img1_ref, img2_ref; int count1 = 0, count2 = 0; bool flag = true; if (img1.Width == img2.Width && img1.Height == img2.Height) { for (int i = 0; i < img1.Width; i++) { for (int j = 0; j < img1.Height; j++) { img1_ref = img1.GetPixel(i, j).ToString(); img2_ref = img2.GetPixel(i, j).ToString(); if (img1_ref != img2_ref) { count2++; flag = false; break; } count1++; } } if (flag == false) MessageBox.Show("Sorry, Images are not same , " + count2 + " wrong pixels found"); else MessageBox.Show(" Images are same , " + count1 + " same pixels found and " + count2 + " wrong pixels found"); } else MessageBox.Show("can not compare this images"); img1.Dispose(); img2.Dispose(); }