Comparing Images as Byte Arrays for Unit Tests

I have a class that creates an Image from Byte[] , along with some other logic, and I'm trying to write a unit test that claims that the Image instance returned from my class is the same as some fake Image in my unit test.

I can not find a reliable way:

  • Start with fake Image \ Byte[] \ Resource \ something.
  • Pass Byte[] representing the fake thing for my class.
  • The Image statement returned from my class matches my fake.

Here is the code that I have provided so far:

 Bitmap fakeBitmap = new Bitmap(1, 1); Byte[] expectedBytes; using (var ms = new MemoryStream()) { fakeBitmap.Save(ms, ImageFormat.Png); expectedBytes = ms.ToArray(); } //This is where the call to class goes Image actualImage; using (var ms = new MemoryStream(expectedBytes)) actualImage = Image.FromStream(ms); Byte[] actualBytes; using (var ms = new MemoryStream()) { actualImage.Save(ms, ImageFormat.Png); actualBytes = ms.ToArray(); } var areEqual = Enumerable.SequenceEqual(expectedBytes, actualBytes); Console.WriteLine(areEqual); var desktop = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); using(StreamWriter sw = new StreamWriter(Path.Combine(desktop, "expectedBytes.txt"))) sw.Write(String.Join(Environment.NewLine, expectedBytes)); using(StreamWriter sw = new StreamWriter(Path.Combine(desktop, "actualBytes.txt"))) sw.Write(String.Join(Environment.NewLine, actualBytes)); 

This always returns false .

+6
source share
2 answers

Try the following:

 public static class Ext { public static byte[] GetBytes(this Bitmap bitmap) { var bytes = new byte[bitmap.Height * bitmap.Width * 3]; BitmapData bitmapData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadWrite, PixelFormat.Format24bppRgb); Marshal.Copy(bitmapData.Scan0, bytes, 0, bytes.Length); bitmap.UnlockBits(bitmapData); return bytes; } } var bitmap = new Bitmap(@"C:\myimg.jpg"); var bitmap1 = new Bitmap(@"C:\myimg.jpg"); var bytes = bitmap.GetBytes(); var bytes1 = bitmap1.GetBytes(); //true var sequenceEqual = bytes.SequenceEqual(bytes1); 
+1
source

I can imagine that Image.Save also updates the metadata inside the image, changing the date / time of this image, which will change your byte array.

0
source

Source: https://habr.com/ru/post/943629/


All Articles