c# - 将图像保存到 MemoryStream - 一般 GDI+ 错误

标签 c# asp.net image-uploading

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

我的问题:我试图将单个图像保存到 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/

相关文章:

c# - 可空属性引发验证错误,而它不应该

c# - 通过托管 C++ 包装器从非托管 C++ dll 运行 C# 函数

c# - System.InvalidCastException : 'The SqlParameterCollection only accepts non-null SqlParameter type objects, not SqlParameter objects.'

c# - 如何使用 C# 在 Postgres 中保存增量值

javascript - ASP.NET 实现一个类似 stackoverflow 搜索框的搜索框

java - 如何从谷歌应用引擎(java)将图像检索到jsp中

php - blueimp/jQuery-File-Upload 与 Laravel 如何整合?

C#进程线程无法写入输出

c# - C#中基于string和bool过滤对象列表

javascript - ajax 使用 codeigniter 传递两种形式