我的应用程序概述:在客户端,使用网络摄像头拍摄一系列快照。提交时,我希望将图像转换为字节数组,并将该字节数组发送到我编写的服务。
我的问题:我试图将单个图像保存到 MemoryStream
,但它继续中断,吐出消息,“GDI+ 中发生一般错误...这是代码块:
// Create array of MemoryStreams
var imageStreams = new MemoryStream[SelectedImages.Count];
for (int i = 0; i < this.SelectedImages.Count; i++)
{
System.Drawing.Image image = BitmapFromSource(this.SelectedImages[i]);
imageStreams[i] = new MemoryStream();
image.Save(imageStreams[i], ImageFormat.Bmp); /* Error is thrown here! */
}
// Combine MemoryStreams into a single byte array (Threw this
// in in case somebody has a better approach)
byte[] bytes = new byte[imageStreams.Sum(s => s.Length)];
for(int i = 0; i < imageStreams.Length; i++)
{
bytes.Concat(imageStreams[i].ToArray());
}
这是我的 BitmapFromSource 方法
// Converts a BitmapSource object to a Bitmap object
private System.Drawing.Image BitmapFromSource(BitmapSource source)
{
System.Drawing.Image bitmap;
using (MemoryStream ms = new MemoryStream())
{
BitmapEncoder encoder = new BmpBitmapEncoder();
encoder.Frames.Add(BitmapFrame.Create(source));
encoder.Save(ms);
bitmap = new System.Drawing.Bitmap(ms);
}
return bitmap;
}
我读到的关于通用 GDI+ 错误的很多内容都指向权限问题,但考虑到我没有保存到文件系统,我看不出这将如何适用于此。此外,我已经看到由于在保存图像之前关闭 MemoryStream 可能会出现此错误,但考虑到我在保存图像之前立即创建 MemoryStream,我也看不出这将如何应用。任何见解将不胜感激。
最佳答案
我认为你的问题实际上出在你的 BitmapFromSource 方法上。
您正在创建一个流,然后从该流创建一个位图,然后丢弃该流,然后尝试将该位图保存到另一个流。但是,Bitmap 类的文档说:
You must keep the stream open for the lifetime of the Bitmap.
当您开始保存该位图时,该位图已经损坏,因为您已经丢弃了原始流。
参见:http://msdn.microsoft.com/en-us/library/z7ha67kw
要解决此问题(请记住,我还没有编写代码,更不用说测试了),请在第一个代码块的第一个 for 循环内创建 MemoryStream,然后将该内存流作为第二个传递给 BitmapFromSource 方法参数。
关于c# - 将图像保存到 MemoryStream - 一般 GDI+ 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11741719/