在没有不安全的情况下重写 LockBits 代码 [英] Rewrite LockBits code without unsafe

查看:32
本文介绍了在没有不安全的情况下重写 LockBits 代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在没有 unsafe 修饰符的情况下重写这段代码?

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));

推荐答案

要获得对位图数据的透明高效访问(比使用 LockBits 的任何复制技术都快),您可以使用以下不需要标记的技术代码不安全(但它确实需要 FullTrust):

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[]

重要提示:尽量避免让对象长时间保持固定(影响 GC 效率),并且不要忘记在 finally 子句中处理位图和 GC 句柄!

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!

您当然也可以创建一个普通的MemoryStream如果你需要一个流,在这个 byte[] 上.

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

这篇关于在没有不安全的情况下重写 LockBits 代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆