5

我的应用程序列出了一个目录中的所有 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 的示例,但是当他们在加载后立即尝试保存时似乎没有人遇到这个问题。

4

3 回答 3

2

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

using (MemoryStream ms = new MemoryStream(currentImageBytes))
{
    pic.Data = TagLib.ByteVector.FromStream(ms);
    f.Tag.Pictures = new TagLib.IPicture[1] { pic };
    if (save)
        f.Save();
}
于 2012-11-28T19:13:29.897 回答
1

您的方法并不是真的错误,只需要更改几件事:

// 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();
于 2014-09-05T08:29:56.783 回答
1

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

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

一探究竟...

于 2012-11-26T05:19:07.940 回答