C# Bitmap存16位图
时间: 2025-01-19 19:05:18 浏览: 48
在C#中,使用`System.Drawing.Bitmap`类可以处理各种位图格式,包括16位图。以下是一些关于如何在C#中处理16位图的基本步骤和示例代码:
1. **创建16位图**:
你可以使用`Bitmap`类的构造函数来创建一个16位图。16位图通常使用16位颜色深度,其中每个像素用两个字节表示。
2. **访问和修改像素数据**:
你可以通过`LockBits`方法锁定位图的位,然后使用`Marshal`类或其他方法访问和修改像素数据。
以下是一个示例代码,展示了如何创建一个16位图并访问其像素数据:
```csharp
using System;
using System.Drawing;
using System.Drawing.Imaging;
using System.Runtime.InteropServices;
class Program
{
static void Main()
{
int width = 100;
int height = 100;
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format16bppRgb555);
// 锁定位图的位
Rectangle rect = new Rectangle(0, 0, bitmap.Width, bitmap.Height);
BitmapData bmpData = bitmap.LockBits(rect, ImageLockMode.ReadWrite, bitmap.PixelFormat);
// 获取位图的首地址
IntPtr ptr = bmpData.Scan0;
// 计算每行的字节数
int bytes = Math.Abs(bmpData.Stride) * bitmap.Height;
byte[] rgbValues = new byte[bytes];
// 复制位图数据到数组
Marshal.Copy(ptr, rgbValues, 0, bytes);
// 修改像素数据(例如,设置所有像素为红色)
for (int i = 0; i < rgbValues.Length; i += 2)
{
rgbValues[i] = 0x1F; // 红色分量
rgbValues[i + 1] = 0x00; // 绿色和蓝色分量
}
// 复制修改后的数据回位图
Marshal.Copy(rgbValues, 0, ptr, bytes);
// 解锁位图的位
bitmap.UnlockBits(bmpData);
// 保存或显示位图
bitmap.Save("output.bmp");
}
}
```
这个示例代码创建了一个100x100像素的16位图,并将所有像素设置为红色。你可以根据需要修改像素数据。
阅读全文
相关推荐


















