问题
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 thebyte[]
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