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

倖福魔咒の 提交于 2019-11-29 07:57:25
Ultraviolet

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);
    }
}

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;
    }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!