c# - 将位图转换为 8bpp 灰度输出作为 c# 中的 8bpp 彩色索引
问题描述
我正在尝试使用下面的代码将位图转换为 8bpp 灰度
private Bitmap ConvertPixelformat(ref Bitmap Bmp)
{
Bitmap myBitmap = new Bitmap(Bmp);
// Clone a portion of the Bitmap object.
Rectangle cloneRect = new Rectangle(0, 0, Bmp.Width, Bmp.Height);
PixelFormat format = PixelFormat.Format8bppIndexed;
Bitmap cloneBitmap = myBitmap.Clone(cloneRect, format);
var pal = cloneBitmap.Palette;
for (i = 0; i < cloneBitmap.Palette.Entries.Length; ++i)
{
var entry = cloneBitmap.Palette.Entries[i];
var gray = (int)(0.30 * entry.R + 0.59 * entry.G + 0.11 * entry.B);
pal.Entries[i] = Color.FromArgb(gray, gray, gray);
}
cloneBitmap.Palette = pal;
cloneBitmap.SetResolution(500.0F, 500.0F);
return cloneBitmap;
}
检查位图图像的属性显示位深度正确设置为 8bpp,但不是灰度,而是彩色索引 8bpp。请指导如何做。
解决方案
检查以下代码:
public static unsafe Bitmap ToGrayscale(Bitmap colorBitmap)
{
int Width = colorBitmap.Width;
int Height = colorBitmap.Height;
Bitmap grayscaleBitmap = new Bitmap(Width, Height, PixelFormat.Format8bppIndexed);
grayscaleBitmap.SetResolution(colorBitmap.HorizontalResolution,
colorBitmap.VerticalResolution);
///////////////////////////////////////
// Set grayscale palette
///////////////////////////////////////
ColorPalette colorPalette = grayscaleBitmap.Palette;
for (int i = 0; i < colorPalette.Entries.Length; i++)
{
colorPalette.Entries[i] = Color.FromArgb(i, i, i);
}
grayscaleBitmap.Palette = colorPalette;
///////////////////////////////////////
// Set grayscale palette
///////////////////////////////////////
BitmapData bitmapData = grayscaleBitmap.LockBits(
new Rectangle(Point.Empty, grayscaleBitmap.Size),
ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed);
Byte* pPixel = (Byte*)bitmapData.Scan0;
for (int y = 0; y < Height; y++)
{
for (int x = 0; x < Width; x++)
{
Color clr = colorBitmap.GetPixel(x, y);
Byte byPixel = (byte)((30 * clr.R + 59 * clr.G + 11 * clr.B) / 100);
pPixel[x] = byPixel;
}
pPixel += bitmapData.Stride;
}
grayscaleBitmap.UnlockBits(bitmapData);
return grayscaleBitmap;
}
此代码将彩色图像转换为灰度图像。
推荐阅读
- c# - 如何在 blazor 服务器端应用程序中扩展身份验证过程?
- c# - .NET Web 应用程序是否可以恢复未完成的下载?
- javascript - 数据在下一行消失
- r - 在R中的不同Excel工作表中附加不同列表的元素
- css - CSS Grid:具有动态行的复杂嵌套网格
- google-app-engine - 部署灵活的 GAE 需要 30 分钟以上
- python - 如何按特征重要性解释文本聚类结果?(DBSCAN)
- gcloud - 如何为 Google Cloud DNS 区域设置默认名称服务器?
- css - 更改 chart.js 中的白色单元格边框颜色
- ios - iOS 通用链接:先到先得 - `didFinishLaunching` 或 `continue userActivity`