2011-07-25 72 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