繁体   English   中英

在C#中将位图转换为8bpp灰度输出作为8bpp彩色索引

[英]converting bitmap to 8bpp grayscale outputs as 8bpp coloured index in c#

我正在尝试使用以下代码将位图转换为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;
    }

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM