如何创建位图深拷贝 [英] How to create a Bitmap deep copy

查看:496
本文介绍了如何创建位图深拷贝的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用程序处理位图和一些目的,我需要创建位图的深层副本。有一种优雅的方式该怎么办呢?

我试过

 位图正是deepcopy = original.Clone();

,以及显然这不会创建一个深拷贝,而浅之一。
我的下一个尝试是创建一个新的位图

 位图正是deepcopy =新位图(原件);

不幸的构造函数是位图(图片),而不是位图(位图)和位图(图片)将我漂亮8bppIndexed像素格式转换成不同的功能。

另一种尝试是使用一个MemoryStream的

 公共静态位图CreateBitmapDeepCopy(位图源)
{
    位图的结果;
    使用(MemoryStream的流=新的MemoryStream())
    {
        source.Save(流ImageFormat.Bmp);
        stream.Seek(0,SeekOrigin.Begin);
        结果=新位图(流);
    }
    返回结果;
}

那么,这也不管用,因为MemoryStream的有位图的整个生命周期过程中被打开。

所以,我总结了我所有的deadends,我很想看到创建位图深拷贝的一个不错的优雅的方式。感谢您的:)


解决方案

  B.Clone(新的Rectangle(0,0,B.Width,B.Height),B.PixelFormat)

I'm dealing with Bitmaps in my application and for some purposes I need to create a deep copy of the Bitmap. Is there an elegant way how to do it?

I tried

Bitmap deepCopy = original.Clone();

,well apparently this doesn't create a deep copy, but shallow one. My next attempt was to create a new Bitmap

Bitmap deepCopy = new Bitmap(original);

Unfortunately this constructor is Bitmap(Image), not Bitmap(Bitmap) and Bitmap(Image) will convert my nice 8bppIndexed Pixelformat into a different one.

Another attempt was to use of a MemoryStream

public static Bitmap CreateBitmapDeepCopy(Bitmap source)
{
    Bitmap result;
    using (MemoryStream stream = new MemoryStream())
    {
        source.Save(stream, ImageFormat.Bmp);
        stream.Seek(0, SeekOrigin.Begin);
        result = new Bitmap(stream);
    }
    return result;
}

Well, this doesn't work either, since the MemoryStream has to be opened during the whole lifetime of Bitmap.

So, I've summed up all my deadends and I'd really like to see a nice elegant way of creating a Bitmap deep copy. Thanks for that :)

解决方案

B.Clone(new Rectangle(0, 0, B.Width, B.Height), B.PixelFormat)

这篇关于如何创建位图深拷贝的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆