比较两个 BitmapImages 以检查它们在 WPF 中是否不同的最快方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/15558107/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Quickest way to compare two BitmapImages to check if they are different in WPF
提问by user1518816
What's the quickest way to compare 2 BitmapImage objects. One is in the Image Source property, and another I create in code.
比较 2 个 BitmapImage 对象的最快方法是什么。一个在 Image Source 属性中,另一个是我在代码中创建的。
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.
如果图像的像素与 Image.Source 中的像素不同,我只想设置图像。
EDIT:
编辑:
AlbumArt is the Image in the view (following MVVM).
AlbumArt 是视图中的 Image(在 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;
...
回答by sa_ddam213
You could compare the bytes of the BitmapImageto check if they are equal
您可以比较 的字节BitmapImage以检查它们是否相等
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
}

