C# 创建16位像素值的灰度图像
时间: 2024-10-23 14:09:05 浏览: 85
在C#中,你可以使用System.Drawing命名空间下的Image类和Bitmap类来创建16位像素值(通常表示为Int16类型)的灰度图像。这里是一个简单的示例:
```csharp
using System.Drawing;
using System.Drawing.Imaging;
public Bitmap CreateGrayscale16BitImage(int width, int height)
{
// 创建一个16位位深度的位图,位深度为2 bytes对应16位
Bitmap bitmap = new Bitmap(width, height, PixelFormat.Format24bppRgb);
// 创建一个Graphics对象,用于绘制和操作图像
Graphics graphics = Graphics.FromImage(bitmap);
// 创建一个ColorMatrix,用于将RGB颜色转换为灰度
ColorMatrix colorMatrix = new ColorMatrix(
new float[][] {
new float[] {0.299f, 0.587f, 0.114f, 0, 0},
new float[] {0.596f, 0.301f, 0.114f, 0, 0},
new float[] {0.211f, 0.523f, 0.312f, 0, 0},
new float[] {0, 0, 0, 1, 0},
new float[] {0, 0, 0, 0, 1}
});
// 创建一个ImageAttributes对象,并设置其颜色矩阵
ImageAttributes imageAttributes = new ImageAttributes();
imageAttributes.SetColorMatrix(colorMatrix);
// 使用Graphics对象和ImageAttributes绘制矩形填充整个图像为灰色
graphics.FillRectangle(Brushes.Gray, 0, 0, width, height, imageAttributes);
return bitmap;
}
// 调用函数创建16位灰度图像
int width = 640;
int height = 480;
Bitmap grayscaleBitmap = CreateGrayscale16BitImage(width, height);
grayscaleBitmap.Save("grayscale_16bit_image.png");
```
在这个示例中,我们首先创建了一个24位的位图,然后通过ColorMatrix将其转换为灰度,最后保存为16位的PNG格式。
阅读全文
相关推荐


















