c# – 将图像保存到MemoryStream-通用GDI错误

我的应用程序概述:在客户端,使用网络摄像头拍摄一系列快照.提交时,我希望将图像转换为字节数组,并将该字节数组发送到我编写的服务.

我的问题:我正在尝试将单个图像保存到MemoryStream,但它继续破坏,吐出消息“GDI中出现一般错误.”当我深入挖掘时,我看到当MemoryStream的缓冲区位置为54时抛出异常.不幸的是,这是一张1.2 mb的照片.这是代码块:

// 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方法.

相关文章

在要实现单例模式的类当中添加如下代码:实例化的时候:frmC...
1、如果制作圆角窗体,窗体先继承DOTNETBAR的:public parti...
根据网上资料,自己很粗略的实现了一个winform搜索提示,但是...
近期在做DSOFramer这个控件,打算自己弄一个自定义控件来封装...
今天玩了一把WMI,查询了一下电脑的硬件信息,感觉很多代码都...
最近在研究WinWordControl这个控件,因为上级要求在系统里,...