Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to compare two images using byte arrays

I want to be able to convert from Byte[] to Image and vice versa.

I've this two methods from here:

public byte[] imageToByteArray(System.Drawing.Image imageIn)
{
    MemoryStream ms = new MemoryStream();
    imageIn.Save(ms,System.Drawing.Imaging.ImageFormat.Gif);
    return  ms.ToArray();
}

public Image byteArrayToImage(byte[] byteArrayIn)
{
     MemoryStream ms = new MemoryStream(byteArrayIn);
     Image returnImage = Image.FromStream(ms);
     return returnImage;
}

They seem to work, but if I do:

byte[] pic = GetImageFromDb();
bool result = pic == imageToByteArray(byteArrayToImage(pic));

I get result = false!

Any way to correct this methods or some different functions to achieve my goal?

Thanks!

like image 212
Diego Avatar asked Jan 06 '12 20:01

Diego


2 Answers

Using == will compare the object references if not overridden.

Since these are two different byte[] objects, the references are different.

You need to compare the byte[] objects item by item in order to confirm that they are identical. You can use SequenceEquals in this case.

like image 100
Oded Avatar answered Oct 10 '22 01:10

Oded


== means that you have a reference to the same object in memory.

This shows how to compare byte arrays in a few different ways.

like image 23
Mark Avenius Avatar answered Oct 10 '22 01:10

Mark Avenius