问题描述
我需要另一个位图的位图深层副本.现在,大多数百家乐凯发k8的解决方案都说类似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 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); } }