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:
Image
\ Byte[]
\ Resource \ something.Byte[]
representing the fake thing to my class.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
.
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With