C# Capture screen to 8-bit (256 color) bitmap

China☆狼群 提交于 2019-12-04 17:49:45

Converting a full color bitmap to 8bpp is a difficult operation. It requires creating a histogram of all the colors in the image and creating a palette that contains an optimized set of colors that best map to the original colors. Then using a technique like dithering or error diffusion to replace the pixels whose colors don't have an exact match with the palette.

This is best left to a professional graphics library, something like ImageTools. There is one cheap way that can be tricked in the .NET framework. You can use the GIF encoder, a file format that has 256 colors. The result isn't the greatest, it uses dithering and that can be pretty visible sometimes. Then again, if you really cared about image quality then you wouldn't use 8bpp anyway.

    public static Bitmap ConvertTo8bpp(Image img) {
        var ms = new System.IO.MemoryStream();   // Don't use using!!!
        img.Save(ms, System.Drawing.Imaging.ImageFormat.Gif);
        ms.Position = 0;
        return new Bitmap(ms);
    }

Capture the screen using a regular PixelFormat and then use Bitmap.Clone() to convert it to an optimized 256 indexed color like this:

public static Bitmap CaptureScreen256()
{
    Rectangle bounds = SystemInformation.VirtualScreen;

    using (Bitmap Temp = new Bitmap(bounds.Width, bounds.Height, PixelFormat.Format24bppRgb))
    {
        using (Graphics g = Graphics.FromImage(Temp))
        {
            g.CopyFromScreen(0, 0, 0, 0, Temp.Size);
        }

        return Temp.Clone(new Rectangle(0, 0, bounds.Width, bounds.Height), PixelFormat.Format8bppIndexed);
    }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!