Skip to content

Instantly share code, notes, and snippets.

@kcargile
Created December 7, 2013 17:43
Show Gist options
  • Save kcargile/7845993 to your computer and use it in GitHub Desktop.
Save kcargile/7845993 to your computer and use it in GitHub Desktop.
.NET extension method for comparing System.Drawing.Images instances by value.
namespace Extensions
{
/// <summary>
/// Contains <see cref="object"/> extension methods.
/// </summary>
public static class ImageExtensions
{
/// <summary>
/// Determines if the two object are equavalent in a way that will not throw if the current obejct is null.
/// </summary>
/// <param name="param">The param.</param>
/// <param name="obj">The obj.</param>
/// <param name="format">The format.</param>
/// <returns>
/// <c>true</c> if the two objects are equivalent; otherwise, <c>false</c>.
/// </returns>
public static bool NullSafeEquals(this Image param, Image obj, ImageFormat format)
{
return null != param ? CompareImages(param, obj, format) : (null == obj);
}
/// <summary>
/// Compares the two images for value equality.
/// </summary>
/// <param name="image1">An image.</param>
/// <param name="image2">Another image.</param>
/// <param name="format">The format.</param>
/// <returns>
/// <c>true</c> if the two images have value equality.
/// </returns>
private static bool CompareImages(Image image1, Image image2, ImageFormat format)
{
Debug.Assert(null != image1);
Debug.Assert(null != image2);
MemoryStream ms1 = new MemoryStream();
MemoryStream ms2 = new MemoryStream();
image1.Save(ms1, format);
image2.Save(ms2, format);
byte[] image1AsByteArray = ms1.ToArray();
byte[] image2AsByteArray = ms2.ToArray();
if (image1AsByteArray.Length != image2AsByteArray.Length)
{
return false;
}
return !image1AsByteArray.Where((t, i) => t != image2AsByteArray[i]).Any();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment