Advertisement
Guest User

Untitled

a guest
Dec 28th, 2012
11
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1.     public class BitmapTests
  2.     {
  3.         [Test]
  4.         public void CompareSameTest()
  5.         {
  6.             using (var first = new Bitmap(@"C:\temp\Blank.bmp"))
  7.             {
  8.                 using (var other = new Bitmap(@"C:\temp\Blank.bmp"))
  9.                 {
  10.                     Assert.IsFalse(first == other);
  11.                 }
  12.             }
  13.         }
  14.  
  15.         [TestCase(@"C:\temp\Blank.bmp", @"C:\temp\Blank.bmp", true)]
  16.         public void CompareBitmapsTest(string firstPath, string otherPath, bool expected)
  17.         {
  18.             using (var first = new Bitmap(firstPath))
  19.             {
  20.                 using (var other = new Bitmap(otherPath))
  21.                 {
  22.                     Assert.AreEqual(expected, BitmapsEqual(first, other));
  23.                 }
  24.             }
  25.         }
  26.  
  27.         public static bool BitmapsEqual(Bitmap source, Bitmap other)
  28.         {
  29.             if (source == other)  // Compare references
  30.             {
  31.                 return true;
  32.             }
  33.             if (source.Size != other.Size)
  34.             {
  35.                 throw new ArgumentException("Cannont compare images of different sizes!");
  36.             }
  37.             using (var sourceHelper = new BitMapHelper(source))
  38.             {
  39.                 using (var otherHelper = new BitMapHelper(other))
  40.                 {
  41.                     return sourceHelper.Bytes.SequenceEqual(otherHelper.Bytes);
  42.                 }
  43.             }
  44.         }
  45.     }
  46.  
  47.     public class BitMapHelper : IDisposable
  48.     {
  49.         private readonly Bitmap _bitmap;
  50.         private BitmapData _bitmapData;
  51.         public byte[] Bytes { get; private set; }
  52.         private int _byteCount;
  53.  
  54.         public BitMapHelper(Bitmap bitmap)
  55.         {
  56.             _bitmap = bitmap;
  57.  
  58.             _byteCount = (bitmap.Width + 1)*(bitmap.Height + 1)*Image.GetPixelFormatSize(bitmap.PixelFormat)/8;
  59.             Bytes = new byte[_byteCount];
  60.             _bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, PixelFormat.Format32bppArgb);
  61.             System.Runtime.InteropServices.Marshal.Copy(_bitmapData.Scan0,Bytes,0,_byteCount);
  62.         }
  63.  
  64.         public void Dispose()
  65.         {
  66.             _bitmap.UnlockBits(_bitmapData);
  67.         }
  68.     }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement