设置 .NET Format16bppGrayScale 图像中的各个像素

发布于 2024-09-13 20:02:57 字数 185 浏览 3 评论 0原文

我正在尝试使用 .NET 在内存中渲染一个需要 16 位灰度的小位图。位图的格式设置为 PixelFormat.Format16bppGrayScale。但是,Bitmap.SetPixel 采用 Color 参数。颜色依次为 R、B 和 G(以及可选的 A)中的每一个占用一个字节。

在绘制位图时如何指定 16 位灰度值而不是 8 位值?

I'm trying to render a small Bitmap in memory with .NET that needs to be 16 bit Grayscale. The bitmap's format is set to PixelFormat.Format16bppGrayScale. However, Bitmap.SetPixel takes a Color argument. Color in turn takes one byte for each of R, B, and G (and optionally A).

How do I specify a 16-bit gray scale value rather than an 8 bit value when drawing to my bitmap?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

时光倒影 2024-09-20 20:02:57

无论图像格式如何,SetPixel() 都非常慢。我在实践中从未使用过它。

您可以使用 LockBits 方法更快地设置像素,该方法允许您快速将托管数据封送到非托管位图字节。

下面是一个示例:

Bitmap bitmap = // ...

// Lock the unmanaged bits for efficient writing.
var data = bitmap.LockBits(
    new Rectangle(0, 0, bitmap.Width, bitmap.Height),
    ImageLockMode.ReadWrite,
    bitmap.PixelFormat);

// Bulk copy pixel data from a byte array:
Marshal.Copy(byteArray, 0, data.Scan0, byteArray.Length);

// Or, for one pixel at a time:
Marshal.WriteInt16(data.Scan0, offsetInBytes, shortValue);

// When finished, unlock the unmanaged bits
bitmap.UnlockBits(data);

请注意,GDI+ 似乎不支持 16bpp 灰度,这意味着 .NET 无法帮助将 16bpp 灰度位图保存到文件或流中。请参阅 http://social。 msdn.microsoft.com/forums/en-US/csharpgeneral/thread/10252c05-c4b6-49dc-b2a3-4c1396e2c3ab

Regardless of the image format, SetPixel() is brutally slow. I never use it in practice.

You can set pixels much faster using the LockBits method, which allows you to quickly marshal managed data to the unmanaged bitmap bytes.

Here is an example of how that might look:

Bitmap bitmap = // ...

// Lock the unmanaged bits for efficient writing.
var data = bitmap.LockBits(
    new Rectangle(0, 0, bitmap.Width, bitmap.Height),
    ImageLockMode.ReadWrite,
    bitmap.PixelFormat);

// Bulk copy pixel data from a byte array:
Marshal.Copy(byteArray, 0, data.Scan0, byteArray.Length);

// Or, for one pixel at a time:
Marshal.WriteInt16(data.Scan0, offsetInBytes, shortValue);

// When finished, unlock the unmanaged bits
bitmap.UnlockBits(data);

Note that 16bpp grayscale appears to be unsupported by GDI+, meaning that .NET doesn't help out with saving a 16bpp grayscale bitmap to a file or a stream. See http://social.msdn.microsoft.com/forums/en-US/csharpgeneral/thread/10252c05-c4b6-49dc-b2a3-4c1396e2c3ab

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文