2009-01-24 103 views
3

我使用的是Visual Basic 9(VS2008)和TagLib。使用TagLib從MP3文件中提取專輯封面 - 有沒有更好的方法來寫這段代碼?

以下代碼從MP3文件中提取專輯封面並將其顯示在PictureBox中。

有沒有更好的方法來寫這段代碼?

Dim file As TagLib.File = TagLib.File.Create(filepath) 

If file.Tag.Pictures.Length >= 1 Then 
    Dim bin As Byte() = DirectCast(file.Tag.Pictures(0).Data.Data, Byte()) 
    PreviewPictureBox.Image = Image.FromStream(New MemoryStream(bin)).GetThumbnailImage(100, 100, Nothing, System.IntPtr.Zero) 
End If 
+0

乍一看,代碼看起來OK我。你有問題嗎? – hmcclungiii 2009-01-24 14:57:57

回答

2

我對TagLib並不熟悉,但看起來好像還沒有更好的方法來編寫它。我可以給出的唯一建議是,您可以利用類型推斷來減少代碼量。如果「Option Infer」當前處於打開狀態,則兩個變量聲明不需要顯式類型。這實際上並沒有改變代碼的質量,它只是減少了代碼的數量。

Option Infer On 
... 
Dim file = TagLib.File.Create(filepath) 

If file.Tag.Pictures.Length >= 1 Then 
    Dim bin = DirectCast(file.Tag.Pictures(0).Data.Data, Byte()) 
    PreviewPictureBox.Image = Image.FromStream(New MemoryStream(bin)).GetThumbnailImage(100, 100, Nothing, System.IntPtr.Zero) 
End If 
3

乍一看,它看起來對我來說沒問題。

您可以添加一些錯誤處理,例如,如果TagLib.File.Create()引發錯誤或返回「Nothing」。此外,如果Tag屬性由於某種原因而爲空,那麼如果您嘗試訪問「.Pictures」,則會引發錯誤。

相關問題