简体   繁体   English

比较图像作为单元测试的字节数组

[英]Comparing Images as Byte Arrays for Unit Tests

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. 我有一个类从Byte[]创建一个Image ,以及其他一些逻辑,我正在尝试编写一个单元测试,断言从我的类返回的Image实例与我在我的一些假Image相同单元测试。

I cannot find a reliable way to: 我找不到一个可靠的方法:

  • Start with a fake Image \\ Byte[] \\ Resource \\ something . 从假的Image \\ Byte[] \\ Resource \\ something开始
  • Pass a Byte[] representing the fake thing to my class. 将代表假Byte[]传递给我的班级。
  • Assert the Image returned from my class is the same as my fake thing . 断言Image从我的类返回是一样的我的假的东西

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 . 这总是返回false

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);

我可以想象Image.Save还会更新图像中的元数据,修改将更改字节数组的图片的日期/时间。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM