問題描述
我需要另一個位圖的位圖深層副本.現在,大多數解決方案都說類似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# 中的位圖創建一個全新的位圖副本的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!