在 .NET Format16bppGrayScale 图像中设置单个像素 [英] Set individual pixels in .NET Format16bppGrayScale image

查看:36
本文介绍了在 .NET Format16bppGrayScale 图像中设置单个像素的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

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

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

推荐答案

无论图像格式如何,SetPixel() 都非常缓慢.我从来没有在实践中使用它.

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

您可以使用 LockBits 方法更快地设置像素,该方法允许您将托管数据快速编组为非托管位图字节.

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

下面是一个例子:

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

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

这篇关于在 .NET Format16bppGrayScale 图像中设置单个像素的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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