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

我的应用程序列出目录中的所有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(); 

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

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

 WebRequest req = WebRequest.Create(urlToImg); WebResponse response = req.GetResponse(); Stream stream = response.GetResponseStream(); currentImage = Image.FromStream(stream); stream.Close(); 

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

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

感谢Jim的帮助,但我无法使用“使用”块让它工作,所以我猜测流仍然在某个地方关闭。 通过存储/保存字节[]而不是图像,我找到了另一种方法来做我想要的事情。 然后使用以下方法保存:

 using (MemoryStream ms = new MemoryStream(currentImageBytes)) { pic.Data = TagLib.ByteVector.FromStream(ms); f.Tag.Pictures = new TagLib.IPicture[1] { pic }; if (save) f.Save(); } 

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

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

看看这个…

你的方法并不是真的,只有一些事情需要改变:

 // 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, System.Drawing.Imaging.ImageFormat.Jpeg); // <-- Error doesn't occur anymore ms.Position = 0; pic.Data = TagLib.ByteVector.FromStream(ms); f.Tag.Pictures = new TagLib.IPicture[1] { pic }; f.save(); ms.Close();