Rewrite LockBits code without unsafe

倾然丶 夕夏残阳落幕 提交于 2019-12-11 04:19:58

问题


How to rewrite this code without unsafe modifier?

var bmpData = bitmap.LockBits(new Rectangle(0, 0, bitmap.Width, bitmap.Height), ImageLockMode.ReadOnly, bitmap.PixelFormat);
var size = Math.Abs(bmpData.Stride) * bitmap.Height;
var stream = new UnmanagedMemoryStream((byte*)bmpData.Scan0, size));

回答1:


To get transparent highly efficient access to the bitmap data (faster than any copy technique with LockBits), you can use the following technique which does not require to mark the code as unsafe (but it does require FullTrust):

  • Create a byte[] for the bitmap data
  • Pin it using a GCHandle.Alloc() call
  • Get the physical address of your byte[] using Marshal.UnsafeAddrOfPinnedArrayElement()
  • Create a Bitmap object on this using the construtor which takes an IntPtr
  • Do your magic on the Bitmap and the byte[]

Important: Try to avoid keeping objects pinned for a long time (hinders GC efficiency), and don't forget to dispose the bitmap and the GC handle in a finally clause!

You can of course also create a normal MemoryStream on this byte[] if you need a stream.



来源:https://stackoverflow.com/questions/17381107/rewrite-lockbits-code-without-unsafe

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!