首页 > 解决方案 > 将位图转换为 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。请指导如何做。

标签: c#imageimage-processingbitmap

解决方案


检查以下代码:

    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;
    }

此代码将彩色图像转换为灰度图像。


推荐阅读