• 首页 首页 icon
  • 工具库 工具库 icon
    • IP查询 IP查询 icon
  • 内容库 内容库 icon
    • 快讯库 快讯库 icon
    • 精品库 精品库 icon
    • 问答库 问答库 icon
  • 更多 更多 icon
    • 服务条款 服务条款 icon

从 C# 的位图创建全新的位图副本

用户头像
it1352
帮助2

问题说明

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

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

正确答案

#1

我想我已经通过使用这个片段解决了这个问题.这个想法是由 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);
    }
}

这篇好文章是转载于:学新通技术网

  • 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
  • 本站站名: 学新通技术网
  • 本文地址: /reply/detail/tangicbee
系列文章
更多 icon
同类精品
更多 icon
继续加载