Using taglib to display the cover art in a Image box in WPF

白昼怎懂夜的黑 提交于 2019-12-18 18:31:21

问题


I'm making a player and I'm stuck in a apparently simple problem. I need to make the cover art of the song to be displayed in one Image box. I found these two solutions:

This:

var file = TagLib.File.Create(filename);
    if (file.Tag.Pictures.Length >= 1)
    {
        var bin = (byte[])(file.Tag.Pictures[0].Data.Data);
        PreviewPictureBox.Image = Image.FromStream(new MemoryStream(bin)).GetThumbnailImage(100, 100, null, IntPtr.Zero);
    }

and this:

System.Drawing.Image currentImage = null;

// In method onclick of the listbox showing all mp3's
TagLib.File f = new TagLib.Mpeg.AudioFile(file);
if (f.Tag.Pictures.Length > 0)
{
  TagLib.IPicture pic = f.Tag.Pictures[0];
  MemoryStream ms = new MemoryStream(pic.Data.Data);
  if (ms != null && ms.Length > 4096)
  {
       currentImage = System.Drawing.Image.FromStream(ms);
       // Load thumbnail into PictureBox
       AlbumArt.Image = currentImage.GetThumbnailImage(100,100, null, System.IntPtr.Zero);
  }
  ms.Close();
}

But both are to Windows Forms, I suppose, because I have problems with them.

I'm not sure which solution makes the most sense. Could anyone give me some pointers?


回答1:


Use System.Windows.Controls.Image to display your images on UI. You must set it's Source property in order to provide image data to render on UI.

// Load you image data in MemoryStream
TagLib.IPicture pic = f.Tag.Pictures[0];
MemoryStream ms = new MemoryStream(pic.Data.Data);
ms.Seek(0, SeekOrigin.Begin);

// ImageSource for System.Windows.Controls.Image
BitmapImage bitmap= new BitmapImage();
bitmap.BeginInit();
bitmap.StreamSource = ms;
bitmap.EndInit();

// Create a System.Windows.Controls.Image control
System.Windows.Controls.Image img = new System.Windows.Controls.Image();
img.Source = bitmap;

Then you can add/place this Image control to UI.



来源:https://stackoverflow.com/questions/17904184/using-taglib-to-display-the-cover-art-in-a-image-box-in-wpf

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!