From 30d3edc9fd3b54a48e6d53dde81b31c3642cc216 Mon Sep 17 00:00:00 2001 From: Jorg Tretter Date: Wed, 14 Jul 2021 10:35:08 -0500 Subject: [PATCH] Convert to 8-Bit Gray scale instead to save space. --- SShot/Program.cs | 29 +++++++++++++++++++++++++---- 1 file changed, 25 insertions(+), 4 deletions(-) diff --git a/SShot/Program.cs b/SShot/Program.cs index 6d8e9dc..1e2e13e 100644 --- a/SShot/Program.cs +++ b/SShot/Program.cs @@ -26,7 +26,7 @@ namespace SShot { Bitmap captureBitmap = new Bitmap(captureRectangle.Width, captureRectangle.Height, PixelFormat.Format32bppArgb); Graphics captureGraphics = Graphics.FromImage(captureBitmap); captureGraphics.CopyFromScreen(captureRectangle.Left, captureRectangle.Top, 0, 0, captureRectangle.Size); - toGrayscale(captureBitmap); + captureBitmap = to8BitGS(captureBitmap); captureBitmap.Save(filename, ImageFormat.Png); } catch (Exception ex) { if (args.Length > 0) { @@ -37,15 +37,36 @@ namespace SShot { } } - private static void toGrayscale(Bitmap bmp) { + private static Bitmap to8BitGS(Bitmap bmp) { + var result = new Bitmap(bmp.Width, bmp.Height, PixelFormat.Format8bppIndexed); + + BitmapData data = result.LockBits(new Rectangle(0, 0, result.Width, result.Height), ImageLockMode.WriteOnly, PixelFormat.Format8bppIndexed); + + // Copy the bytes from the image into a byte array + byte[] bytes = new byte[data.Width * data.Height ]; + Marshal.Copy(data.Scan0, bytes, 0, bytes.Length); + for (int y = 0; y < bmp.Height; y++) { for (int x = 0; x < bmp.Width; x++) { var c = bmp.GetPixel(x, y); - int rgb = (c.R + c.G + c.B) / 3; + var rgb = (byte)((c.R + c.G + c.B) / 3); - bmp.SetPixel (x,y,Color.FromArgb(c.A, rgb,rgb,rgb)); + bytes[y * data.Stride + x] = rgb; } } + + // Copy the bytes from the byte array into the image + Marshal.Copy(bytes, 0, data.Scan0, bytes.Length); + + result.UnlockBits(data); + + ColorPalette pal = result.Palette; + for (int i = 0; i < 256; i++) { + pal.Entries[i] = Color.FromArgb(255, i, i, i); + } + result.Palette = pal; + + return result; } } }