Creating a completely new copy of bitmap from a bitmap in C#

前端 未结 2 1904
盖世英雄少女心
盖世英雄少女心 2020-12-10 19:24

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

相关标签:
2条回答
  • 2020-12-10 19:53

    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);
        }
    }
    
    0 讨论(0)
  • 2020-12-10 19:56

    You can use like this it is smaller and more elegant way.

    public static Bitmap GetCopyOf(Bitmap originalImage)
        {
        Bitmap copy = new Bitmap(originalImage.Width, originalImage.Height);
        using (Graphics graphics = Graphics.FromImage(copy))
        {
          Rectangle imageRectangle = new Rectangle(0, 0, copy.Width, copy.Height);
          graphics.DrawImage( originalImage, imageRectangle, imageRectangle, GraphicsUnit.Pixel);
        }
        return copy;
        }
    
    0 讨论(0)
提交回复
热议问题