微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

原文地址:https://www.jb51.cc/csharp/94653.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐