AForge.Imaging.UnmanagedImage.GetPixel C# (CSharp) Method

GetPixel() public method

Get color of the pixel with the specified coordinates.

In the case if the image has 8 bpp grayscale format, the method will return a color with all R/G/B components set to same value, which is grayscale intensity.

The method supports only 8 bpp grayscale images and 24/32 bpp color images so far.

The specified pixel coordinate is out of image's bounds. Pixel format of this image is not supported by the method.
public GetPixel ( int x, int y ) : Color
x int X coordinate of the pixel to get.
y int Y coordinate of the pixel to get.
return Color
        public Color GetPixel( int x, int y )
        {
            if ( ( x < 0 ) || ( y < 0 ) )
            {
                throw new ArgumentOutOfRangeException( "x", "The specified pixel coordinate is out of image's bounds." );
            }

            if ( ( x >= width ) || ( y >= height ) )
            {
                throw new ArgumentOutOfRangeException( "y", "The specified pixel coordinate is out of image's bounds." );
            }

            Color color = new Color( );

            unsafe
            {
                int pixelSize = Bitmap.GetPixelFormatSize( pixelFormat ) / 8;
                byte* ptr = (byte*) imageData.ToPointer( ) + y * stride + x * pixelSize;

                switch ( pixelFormat )
                {
                    case PixelFormat.Format8bppIndexed:
                        color = Color.FromArgb( *ptr, *ptr, *ptr );
                        break;

                    case PixelFormat.Format24bppRgb:
                    case PixelFormat.Format32bppRgb:
                        color = Color.FromArgb( ptr[RGB.R], ptr[RGB.G], ptr[RGB.B] );
                        break;

                    case PixelFormat.Format32bppArgb:
                        color = Color.FromArgb( ptr[RGB.A], ptr[RGB.R], ptr[RGB.G], ptr[RGB.B] );
                        break;

                    default:
                        throw new UnsupportedImageFormatException( "The pixel format is not supported: " + pixelFormat );
                }
            }

            return color;
        }

Same methods

UnmanagedImage::GetPixel ( IntPoint point ) : Color

Usage Example

Beispiel #1
0
        public static int AvgColor(System.Drawing.Image img, int forceZeroBelow)
        {
            long total = 0;

            AForge.Imaging.UnmanagedImage umimg = AForge.Imaging.UnmanagedImage.FromManagedImage(new Bitmap(img));
            for (int y = 0; y < umimg.Height; y++)
            {
                for (int x = 0; x < umimg.Width; x++)
                {
                    Color c = umimg.GetPixel(x, y);
                    total += forceZeroBelow > ((c.R + c.G + c.B) / 3) ? 0 : 255;
                }
            }
            return((int)((long)total / ((long)umimg.Width * (long)umimg.Height)));
        }
All Usage Examples Of AForge.Imaging.UnmanagedImage::GetPixel