破坏流导致破坏位图

Destroying stream cause destroying the bitmap

我有类似的东西:

       public Bitmap GetBitmap()
       {         
            Byte[] byteArray= bring it from somewhere    
            using (Stream stream = new MemoryStream(byteArray))
            {
                return new Bitmap(stream);
            }
        }

当我在外部使用此方法时,Bitmap 被压碎了。但如果我进入 "using" 范围,位图将存在并且工作正常。似乎处理流导致处理位图.. 问题是: 我需要一些深拷贝吗?我应该如何执行?

dispose时Bitmap会丢失,所以确实需要深拷贝。 最终你的代码应该是:

public static Bitmap GetBitmap()
{
    byte[] byteArray = bring it from somewhere
    using (Stream stream = new MemoryStream(byteArray))
    {
        var tempBitmap = new Bitmap(stream);
        return new Bitmap(tempBitmap); // This will deep-copy the Bitmap
    }
}

顺便说一句,通常原始类型,如byte,都是小写的。