C#学习教程:在C#中从位图创建位图的全新副本现在,大多数解决方案都是这样的,它不是深拷贝。这意味着当我锁定原始位图时,副本也被锁定,因为克隆是原始位图的浅表副本。现在以下似乎对我有用,但我不确定它是否适用于所有情况。publicstaticBitmapGetCopyOf(BitmaporiginalImage){Rectanglerect=newRectangle(0,0,originalImage.Width,originalImage.Height);位图returnImage=newBitmap(originalImage.Width,originalImage.Height,originalImage.PixelFormat);BitmapDatasrcData=originalImage.LockBits(rect,ImageLockMode.ReadOnly,originalImage.PixelFormat);BitmapDatadestData=returnImage.LockBits(rect,ImageLockMode.WriteOnly,originalImage.PixelFormat);intdataLength=Math.Abs??(srcData.Stride)*srcData.Height;byte[]data=newbyte[dataLength];Marshal.Copy(srcData.Scan0,??data,0,data.Length);Marshal.Copy(数据,0,destData.Scan0,??data.Length);destData.Stride=源数据。大步前进;如果(originalImage.Palette.Entries.Length!=0)returnImage.Palette=originalImage.Palette;originalImage.UnlockBits(srcData);returnImage.UnlockBits(destData);返回返回图像;我需要一种更好、更优雅的方式来做到这一点。否则,请指出上述代码可能会失败的一些情况。TIA我想我已经通过使用这个片段解决了这个问题。Lanorkin在评论中给出了想法,并在此处找到了实现。希望这可以帮助。publicstaticTClone(Tsource){if(!typeof(T).IsSerializable){thrownewArgumentException("类型必须是可序列化的。","source");}//不要序列化空对象,只需返回该对象的默认值if(Object.ReferenceEquals(source,null)){returndefault(T);}IFormatter格式化程序=newBinaryFormatter();流stream=newMemoryStream();使用(流){formatter.Serialize(流,源);stream.Seek(0,SeekOrigin.Begin);返回(T)格式化程序。反序列化(流);你可以像这样以更小更优雅的方式使用它。以上就是C#学习教程:CreateabrandnewbitmapcopyfromabitmapinC#分享的所有内容,如果对大家有用,需要详细了解C#学习教程,希望大家多加关注——公众号staticBitmapGetCopyOf(BitmaporiginalImage){Bitmapcopy=newBitmap(originalImage.Width,originalImage.Height);使用(Graphicsgraphics=Graphics.FromImage(copy)){RectangleimageRectangle=newRectangle(0,0,copy.Width,copy.Height);graphics.DrawImage(originalImage,imageRectangle,imageRectangle,GraphicsUnit.Pixel);}返回副本;}本文收集自网络,不代表立场。如涉及侵权,请点击右侧联系管理员删除。如需转载请注明出处:
