Accord.Imaging.Formats.Tools.CreateGrayscaleImage C# (CSharp) Method

CreateGrayscaleImage() public static method

Create and initialize new grayscale image.

Accord.Imaging.Image.CreateGrayscaleImage() function could be used instead, which does the some. But it was not used to get rid of dependency on AForge.Imaing library.

public static CreateGrayscaleImage ( int width, int height ) : Bitmap
width int Image width.
height int Image height.
return System.Drawing.Bitmap
        public static Bitmap CreateGrayscaleImage( int width, int height )
        {
            // create new image
            Bitmap image = new Bitmap( width, height, PixelFormat.Format8bppIndexed );
            // get palette
            ColorPalette cp = image.Palette;
            // init palette with grayscale colors
            for ( int i = 0; i < 256; i++ )
            {
                cp.Entries[i] = Color.FromArgb( i, i, i );
            }
            // set palette back
            image.Palette = cp;
            // return new image
            return image;
        }

Usage Example

Example #1
0
        // Load P2 PGM image (grayscale PNM image with ascii encoding)
        private static unsafe Bitmap ReadP2Image(TextReader stream, int width, int height, int maxValue)
        {
            double scalingFactor = 255 / (double)maxValue;

            // create new bitmap and lock it
            Bitmap     image     = Tools.CreateGrayscaleImage(width, height);
            BitmapData imageData = image.LockBits(ImageLockMode.WriteOnly);

            int   stride = imageData.Stride;
            byte *ptr    = (byte *)imageData.Scan0.ToPointer();
            int   offset = imageData.Stride - imageData.Width;

            // load all rows
            string all = stream.ReadToEnd();

            string[] values = all.Split(emptyChars, StringSplitOptions.RemoveEmptyEntries);

            for (int y = 0, z = 0; y < height; y++)
            {
                // fill next image row
                for (int x = 0; x < width; x++, ptr++, z++)
                {
                    *ptr = (byte)(scalingFactor * Byte.Parse(values[z]));
                }
                ptr += offset;
            }

            // unlock image and return it
            image.UnlockBits(imageData);
            return(image);
        }
All Usage Examples Of Accord.Imaging.Formats.Tools::CreateGrayscaleImage