从 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);
}
}
这篇好文章是转载于:学新通技术网
- 版权申明: 本站部分内容来自互联网,仅供学习及演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,请提供相关证据及您的身份证明,我们将在收到邮件后48小时内删除。
- 本站站名: 学新通技术网
- 本文地址: /reply/detail/tangicbee
-
YouTube API 不能在 iOS (iPhone/iPad) 工作,但在桌面浏览器工作正常?
it1352 07-30 -
iPhone,一张图像叠加到另一张图像上以创建要保存的新图像?(水印)
it1352 07-17 -
保持在后台运行的 iPhone 应用程序完全可操作
it1352 07-25 -
在android同时打开手电筒和前置摄像头
it1352 09-28 -
使用c++17更新时出现G++编译器警告
it1352 06-18 -
使用 iPhone 进行移动设备管理
it1352 07-23 -
扫描 NFC 标签时是否可以启动应用程序?
it1352 08-02 -
Android App 和三星 Galaxy S4 不兼容
it1352 07-20 -
复制文件夹/文件而不修改属性?
it1352 07-15 -
在不打开短信界面的情况下从 iPhone 应用发送短信?
it1352 07-25