我正在尝试使用下面的代码将位图转换为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。请指导如何做。
答案 0 :(得分:2)
检查以下代码:
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;
}
此代码将彩色图像转换为灰度图像。