2013-04-25 33 views
6

我有一个类,从Byte[]创建一个Image,以及一些其他逻辑,我试图写一个单元测试,声明从我的类返回的Image实例是与我的单元测试中的一些假冒Image相同。比较图像作为单元测试的字节阵列

我无法找到一个可靠的方法:

  • 开始用假Image \ Byte[] \资源\ 东西
  • 通过一个Byte[]代表假冒东西到我的课。
  • 断言我的班级返回的Image与我的假东西一样。

这里是我想出了迄今为止代码:

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

这总是返回false

回答

0

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

1

尝试这种情况:

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

使用'GetBytes会(fakeBitmap)'返回一个3字节数组满零点。将它传递给'Image.FromStream()'会抛出一个'ArgumentException'。 – DaveShaw 2013-04-25 15:34:22

+0

因为你得到raw-bytes'Image'不能用原始字节工作。当你使用这个方法'fakeBitmap.Save(ms,ImageFormat.Png);'你得到指定格式的字节。 – 2013-04-25 15:47:02