简体   繁体   中英

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

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 bitmap image, but it causes flickering because it keeps setting the same image over and over.

I'd like to only set the image if its pixels are different from the one in Image.Source.

EDIT:

AlbumArt is the Image in the view (following MVVM).

Some code (running in the view code-behind):

Task.Factory.StartNew(() =>
    {
        while (((App)Application.Current).Running)
        {
            Thread.Sleep(1000);

            Application.Current.Dispatcher.Invoke(new Action(() =>
            {
                if ((this.DataContext as AudioViewModel).CurrentDevice != null)
                {
                    if ((((this.DataContext as AudioViewModel).CurrentDevice) as AUDIO).SupportsAlbumArt)
                    {
                        BitmapImage image = new BitmapImage();
                        image.BeginInit();
                        image.UriSource = new Uri((((this.DataContext as AudioViewModel).CurrentDevice) as AUDIO).AlbumArt);
                        image.CacheOption = BitmapCacheOption.None;
                        image.CreateOptions = BitmapCreateOptions.IgnoreImageCache;
                        image.EndInit();

                        AlbumArt.Source = image;
                        ...

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
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM