Creating a completely new copy of bitmap from a bitmap in C#(从 C# 中的位图创建一个全新的位图副本)
问题描述
我需要另一个位图的位图深层副本.现在,大多数解决方案都说类似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
推荐答案
我想我已经通过使用这个片段解决了这个问题.这个想法是由 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# 中的位图创建一个全新的位图副本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:从 C# 中的位图创建一个全新的位图副本


- Windows 喜欢在 LINUX 中使用 MONO 进行服务开发? 2022-01-01
- C# 通过连接字符串检索正确的 DbConnection 对象 2022-01-01
- 是否可以在 .Net 3.5 中进行通用控件? 2022-01-01
- CanBeNull和ReSharper-将其用于异步任务? 2022-01-01
- 在 LINQ to SQL 中使用 contains() 2022-01-01
- 为什么 C# 中的堆栈大小正好是 1 MB? 2022-01-01
- 在 C# 中异步处理项目队列 2022-01-01
- Azure Active Directory 与 MVC,客户端和资源标识同一 2022-01-01
- 使用 rss + c# 2022-01-01
- 带问号的 nvarchar 列结果 2022-01-01