Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Comparing Images as Byte Arrays for Unit Tests

Tags:

c#

.net

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

I cannot find a reliable way to:

  • Start with a fake Image \ Byte[] \ Resource \ something.
  • Pass a Byte[] representing the fake thing to my class.
  • Assert the Image returned from my class is the same as my fake thing.

Here's the code I have come up with 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.

like image 373
DaveShaw Avatar asked Apr 25 '13 14:04

DaveShaw


1 Answers

Try this:

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);
like image 114
Vyacheslav Volkov Avatar answered Nov 08 '22 20:11

Vyacheslav Volkov