SoFunction
Updated on 2025-03-07

Detailed explanation of the implementation method based on C# image grayscale, grayscale inversion and binarization


  /// <summary>
/// Image binary 1: Take the average grayscale of the picture as the threshold value, all those below this value are 0, and all those above this value are 255
        /// </summary>
        /// <param name="bmp"></param>
        /// <returns></returns>
        public static Bitmap ConvertTo1Bpp1(Bitmap bmp)
        {
            int average = 0;
            for (int i = 0; i < ; i++)
            {
                for (int j = 0; j < ; j++)
                {
                    Color color = (i, j);
                    average += ;                    
                }
            }
            average = (int)average / ( * );

            for (int i = 0; i < ; i++)
            {
                for (int j = 0; j < ; j++)
                {
//Get the RGB color of the pixels of this point
                    Color color = (i, j);
                    int value = 255 - ;
                    Color newColor = value > average ? (0, 0, 0): (255,

255, 255);                   
                    (i, j, newColor);
                }
            }
            return bmp;
        }

        /// <summary>
/// Image binary 2
        /// </summary>
        /// <param name="img"></param>
        /// <returns></returns>
        public static Bitmap ConvertTo1Bpp2(Bitmap img)
        {
            int w = ;
            int h = ;
            Bitmap bmp = new Bitmap(w, h, PixelFormat.Format1bppIndexed);
            BitmapData data = (new Rectangle(0, 0, w, h), ,

PixelFormat.Format1bppIndexed);
            for (int y = 0; y < h; y++)
            {
                byte[] scan = new byte[(w + 7) / 8];
                for (int x = 0; x < w; x++)
                {
                    Color c = (x, y);
                    if (() >= 0.5) scan[x / 8] |= (byte)(0x80 >> (x % 8));
                }
                (scan, 0, (IntPtr)((int)data.Scan0 + * y), );
            }
            return bmp;
        }