Quickest way to compare two BitmapImages to check if they are different in WPF

后端 未结 1 1894
野趣味
野趣味 2021-01-03 08:30

What\'s the quickest way to compare 2 BitmapImage objects. One is in the Image Source property, and another I create in code.

I can set the image source with the new

相关标签:
1条回答
  • 2021-01-03 08:52

    You could compare the bytes of the BitmapImage to check if they are equal

    Something like:

    public static class BitmapImageExtensions
    {
        public static bool IsEqual(this BitmapImage image1, BitmapImage image2)
        {
            if (image1 == null || image2 == null)
            {
                return false;
            }
            return image1.ToBytes().SequenceEqual(image2.ToBytes());
        }
    
        public static byte[] ToBytes(this BitmapImage image)
        {
            byte[] data = new byte[] { };
            if (image != null)
            {
                try
                {
                    var encoder = new BmpBitmapEncoder();
                    encoder.Frames.Add(BitmapFrame.Create(image));
                    using (MemoryStream ms = new MemoryStream())
                    {
                        encoder.Save(ms);
                        data = ms.ToArray();
                    }
                    return data;
                }
                catch (Exception ex)
                {
                }
            }
            return data;
        }
    }
    

    Usage:

    BitmapImage image1 = ..............
    BitmapImage image2 = ................
    
    if (image1.IsEqual(image2))
    {
        // same image
    }
    
    0 讨论(0)
提交回复
热议问题