2011-07-25 68 views
0

我试图用WPF文件和文件夹的图标填充树状视图,就像Windows资源管理器一样。问题是,这是非常缓慢的加载,因为我使用一个转换器,只是调用如何比较两个System.Drawing.Icon项目

return Imaging.CreateBitmapSourceFromHIcon(icon.Handle, new Int32Rect(0, 0, c.Width, c.Height), BitmapSizeOptions.FromEmptyOptions()); 

我认为这为每个文件/文件夹中,我得到一个新的图标。我用ManagedWinAPI扩展名检索图像。所以现在,我正在计划使用可以比较图标的字典。

但我怎样才能比较两个System.Drawing.Icon对象?因为参考文献总是不同(测试)。我不需要像素比较器,因为我不认为这会加快我的过程。

更新

@Roy Dictus'答复考虑在内,该词典还告诉我,有列表中没有相等的对象:

Dictionary<byte[], ImageSource> data = new Dictionary<byte[], ImageSource>(); 

public object Convert(object value, Type targetType, object parameter, System.Globalization.CultureInfo culture) 
{ 
    Icon c = (Icon)value; 
    Bitmap bmp = c.ToBitmap(); 

    // hash the icon 
    ImageConverter converter = new ImageConverter(); 
    byte[] rawIcon = converter.ConvertTo(bmp, typeof(byte[])) as byte[]; 

    MD5CryptoServiceProvider md5 = new MD5CryptoServiceProvider(); 
    byte[] hash = md5.ComputeHash(rawIcon); 

    ImageSource result; 

    data.TryGetValue(hash, out result); 

    if (result == null) 
    { 
     PrintByteArray(hash); // custom method, prints the same values for two folder icons 
     result = Imaging.CreateBitmapSourceFromHIcon(c.Handle, new Int32Rect(0, 0, c.Width, c.Height), BitmapSizeOptions.FromEmptyOptions()); 
     data.Add(hash, result); 
    } 
    else 
    { 
     Console.WriteLine("Found equal icons"); 
    } 

    return result; 
} 
+0

你怎么知道要加载哪个图标? –

+0

有*必须*是比使用'CreateBitmapSourceFromHIcon'更有效的访问/转换图标的方法。这是为了处理非托管图标数据。 –

+0

@Damien我还没有找到,这似乎是一个把它带到WFP ImageSource。 – Marnix

回答

1

你将不得不要么比较位图,要么根据位图计算散列值,然后比较这些值。

This post关于Visual C#踢脚板显示了如何从位图计算散列值。

编辑:一些额外的信息,基于OP如何修改他的问题:

我不会用字节[]作为字典键 - 我不知道实现IComparable的。如果你可以将字节数组转换为一个字符串,它实现了IComparable,那么它可能会起作用。

您可以将字节数组转换为字符串,像这样:

StringBuilder sb = new StringBuilder(); 
for (int i = 0; i < result.Length; i++) 
{ 
    sb.Append(result[i].ToString("X2")); 
} 
+0

好文章!哈希确实似乎给出了相同的两个图标相同的字节[]。但不知何故,我的字典仍然说,关键不在列表中。我将在我的问题中发布完整的转换方法。 – Marnix

0

使用icon.Handle作为字典键。

+1

已经尝试过这一点,但似乎它们也不同(即使是两个文件夹)。 – Marnix