从C#中的位图创建一个全新的位图副本 [英] Creating a completely new copy of bitmap from a bitmap in C#

查看:946
本文介绍了从C#中的位图创建一个全新的位图副本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要从另一个位图获得位图的深层副本。现在,大多数解决方案都说像这个,这不是深层拷贝。这意味着当我锁定原始位图时,副本也会被锁定,因为克隆是原始位图的浅拷贝。现在以下似乎对我有用,但我不确定它是否适用于所有情况。

I need a deep copy of bitmap from another bitmap. Now, most of the solutions say something like this, which is not a deep copy. Meaning that when I lock the original bitmap, then the copy gets locked too, as the clone is a shallow copy of the original bitmap. Now the following seems to work for me, but I am not sure that will work in all cases.

public static Bitmap GetCopyOf(Bitmap originalImage)
{
    Rectangle rect = new Rectangle(0, 0, originalImage.Width, originalImage.Height);
    Bitmap retrunImage = new Bitmap(originalImage.Width, originalImage.Height, originalImage.PixelFormat);
    BitmapData srcData = originalImage.LockBits(rect, ImageLockMode.ReadOnly, originalImage.PixelFormat);
    BitmapData destData = retrunImage.LockBits(rect, ImageLockMode.WriteOnly, originalImage.PixelFormat);
    int dataLength = Math.Abs(srcData.Stride) * srcData.Height;
    byte[] data = new byte[dataLength];
    Marshal.Copy(srcData.Scan0, data, 0, data.Length);
    Marshal.Copy(data, 0, destData.Scan0, data.Length);
    destData.Stride = srcData.Stride;
    if (originalImage.Palette.Entries.Length != 0)
        retrunImage.Palette = originalImage.Palette;
    originalImage.UnlockBits(srcData);
    retrunImage.UnlockBits(destData);
    return retrunImage;
}

我需要更好,更优雅的方式。否则,请指出一些上述代码可能失败的情况。 TIA

I need better and more elegant way of doing this. Otherwise, just point me some cases where the above code may fail. TIA

推荐答案

我想我已经通过使用这个片段解决了这个问题。这个想法是由评论中的 Lanorkin 给出的,并且找到了实现此处。希望这会有所帮助。

I think I have solved the problem by using this snippet. The idea was given by Lanorkin in the comment and the implementaion is found here. Hope this will help somebody later.

public static T Clone<T>(T source)
{
    if (!typeof(T).IsSerializable)
    {
        throw new ArgumentException("The type must be serializable.", "source");
    }

    // Don't serialize a null object, simply return the default for that object
    if (Object.ReferenceEquals(source, null))
    {
        return default(T);
    }

    IFormatter formatter = new BinaryFormatter();
    Stream stream = new MemoryStream();
    using (stream)
    {
        formatter.Serialize(stream, source);
        stream.Seek(0, SeekOrigin.Begin);
        return (T)formatter.Deserialize(stream);
    }
}

这篇关于从C#中的位图创建一个全新的位图副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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