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

Noberto Pessôa picture Noberto Pessôa · Jul 28, 2013 · Viewed 7.5k times · Source

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?

Answer

Nitesh picture Nitesh · Jul 28, 2013

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.