1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
| private bool CompareBitmaps(Image left, Image right){ if (object.Equals(left, right)) return true; if (left == null || right == null) return false; if (!left.Size.Equals(right.Size) || !left.PixelFormat.Equals(right.PixelFormat)) return false; Bitmap leftBitmap = left as Bitmap; Bitmap rightBitmap = right as Bitmap; if (leftBitmap == null || rightBitmap == null) return true; #region Code taking more time for comparison for (int col = 0; col < left.Width; col++) { for (int row = 0; row < left.Height; row++) { if (!leftBitmap.GetPixel(col, row).Equals(rightBitmap.GetPixel(col, row))) return false; } } #endregion return true;} |
40 ms Bitmap.LockBits() and Bitmap.UnlockBits()
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
| private bool CompareBitmaps(Image left, Image right){ if (object.Equals(left, right)) return true; if (left == null || right == null) return false; if (!left.Size.Equals(right.Size) || !left.PixelFormat.Equals(right.PixelFormat)) return false; Bitmap leftBitmap = left as Bitmap; Bitmap rightBitmap = right as Bitmap; if (leftBitmap == null || rightBitmap == null) return true; #region Optimized code for performance int bytes = left.Width * left.Height * (Image.GetPixelFormatSize(left.PixelFormat) / 8); bool result = true; byte[] b1bytes = new byte[bytes]; byte[] b2bytes = new byte[bytes]; BitmapData bmd1 = leftBitmap.LockBits(new Rectangle(0, 0, leftBitmap.Width - 1, leftBitmap.Height - 1), ImageLockMode.ReadOnly, leftBitmap.PixelFormat); BitmapData bmd2 = rightBitmap.LockBits(new Rectangle(0, 0, rightBitmap.Width - 1, rightBitmap.Height - 1), ImageLockMode.ReadOnly, rightBitmap.PixelFormat); Marshal.Copy(bmd1.Scan0, b1bytes, 0, bytes); Marshal.Copy(bmd2.Scan0, b2bytes, 0, bytes); for (int n = 0; n <= bytes - 1; n++) { if (b1bytes[n] != b2bytes[n]) { result = false; break; } } leftBitmap.UnlockBits(bmd1); rightBitmap.UnlockBits(bmd2); #endregion return result;} |