使用TagLib sharp加载相册艺术,然后将其保存到C#中的相同/不同文件会导致内存错误

Ovi*_*n08 5 c# mp3 taglib

我的应用程序列出目录中的所有MP3,当用户选择文件时,它会加载标签信息,包括专辑封面.将该艺术加载到用户保存数据时使用的变量中.该艺术品也被加载到图片框中供用户查看.

// Global to all methods
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();
}

// Method to save album art
TagLib.Picture pic = new TagLib.Picture();
pic.Type = TagLib.PictureType.FrontCover;
pic.MimeType = System.Net.Mime.MediaTypeNames.Image.Jpeg;
pic.Description = "Cover";
MemoryStream ms = new MemoryStream();
currentImage.Save(ms, ImageFormat.Jpeg); // <-- Error occurs on this line
ms.Position = 0;
pic.Data = TagLib.ByteVector.FromStream(ms);
f.Tag.Pictures = new TagLib.IPicture[1] { pic };
f.save();
ms.Close();
Run Code Online (Sandbox Code Playgroud)

如果我加载图像并尝试立即保存它,我会得到"尝试读取或写入受保护的内存.这通常表明其他内存已损坏." 如果我尝试将currentImage保存为ImageFormat.Bmp,我会得到"GDI +中发生的一般错误".

如果我从这样的URL加载图像,我的保存方法可以正常工作:

WebRequest req = WebRequest.Create(urlToImg);
WebResponse response = req.GetResponse();
Stream stream = response.GetResponseStream();
currentImage = Image.FromStream(stream);
stream.Close();
Run Code Online (Sandbox Code Playgroud)

所以我猜测当用户从列表框中选择一个MP3时,我将图像加载到currentImage的方式存在问题.

我已经找到了许多加载和保存图像到mp3的例子,但是当他们尝试在加载后立即保存图片时似乎没有人遇到这个问题.

J.W*_*lls 1

您的流内容应该使用块,这将自动处理您的内容并关闭它们。不是很重要,但更容易管理。

您的一般 GDI+ 错误可能是因为您正在尝试对流已关闭的文件执行操作或调用方法。

一探究竟...