为了账号安全,请及时绑定邮箱和手机立即绑定

Image.Save(..)抛出GDI +异常,因为内存流已关闭

Image.Save(..)抛出GDI +异常,因为内存流已关闭

C#
胡说叔叔 2019-07-26 15:14:47
Image.Save(..)抛出GDI +异常,因为内存流已关闭我有一些二进制数据,我想保存为图像。当我尝试保存图像时,如果用于创建图像的内存流在保存之前关闭,则会引发异常。我这样做的原因是因为我正在动态创建图像,因此我需要使用内存流。这是代码:[TestMethod]public void TestMethod1(){     // Grab the binary data.     byte[] data = File.ReadAllBytes("Chick.jpg");     // Read in the data but do not close, before using the stream.     Stream originalBinaryDataStream = new MemoryStream(data);     Bitmap image = new Bitmap(originalBinaryDataStream);     image.Save(@"c:\test.jpg");     originalBinaryDataStream.Dispose();     // Now lets use a nice dispose, etc...     Bitmap2 image2;     using (Stream originalBinaryDataStream2 = new MemoryStream(data))     {         image2 = new Bitmap(originalBinaryDataStream2);     }     image2.Save(@"C:\temp\pewpew.jpg"); // This throws the GDI+ exception.}有没有人对如何在关闭流的情况下保存图像有任何建议?我不能依赖开发人员记住在保存图像后关闭流。实际上,开发人员没有使用内存流生成映像的IDEA(因为它发生在其他地方的其他代码中)。我真的很困惑:(
查看完整描述

3 回答

?
慕桂英546537

TA贡献1848条经验 获得超10个赞

GDI +中发生了一般错误。 也可能是因为保存路径不正确!我花了半天才注意到这一点。因此,请确保您已双重检查路径以保存图像。


查看完整回答
反对 回复 2019-07-26
?
蓝山帝景

TA贡献1843条经验 获得超7个赞

复制位图。您必须在位图的生命周期内保持流打开。

绘制图像时:System.Runtime.InteropServices.ExternalException:GDI中发生一般错误

    public static Image ToImage(this byte[] bytes)
    {
        using (var stream = new MemoryStream(bytes))
        using (var image = Image.FromStream(stream, false, true))
        {
            return new Bitmap(image);
        }
    }

    [Test]
    public void ShouldCreateImageThatCanBeSavedWithoutOpenStream()
    {
        var imageBytes = File.ReadAllBytes("bitmap.bmp");

        var image = imageBytes.ToImage();

        image.Save("output.bmp");
    }


查看完整回答
反对 回复 2019-07-26
  • 3 回答
  • 0 关注
  • 847 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信