System.Drawing.Bitmap.GetPixel C# (CSharp) Method

GetPixel() public method

public GetPixel ( int x, int y ) : Color
x int
y int
return Color
        public Color GetPixel(int x, int y)
        {
            if (x < 0 || x > NativeCGImage.Width - 1)
                throw new InvalidEnumArgumentException ("Parameter must be positive and < Width.");
            if (y < 0 || y > NativeCGImage.Height - 1)
                throw new InvalidEnumArgumentException ("Parameter must be positive and < Height.");

            // Need more tests to see if we need this call.
            MakeSureWeHaveAnAlphaChannel ();

            // We are going to cheat here and instead of reading the bytes of the original image
            // parsing from there a pixel and converting to a format we will just create
            // a 1 x 1 image of the pixel that we want.  I am supposing this should be really
            // fast.
            var pixelImage = NativeCGImage.WithImageInRect (new CGRect (x,y,1,1));

            var pData = pixelImage.DataProvider;
            var nData = pData.CopyData ();

            // We may have to parse out the bytes with 4 or 3 bytes per pixel later.
            var pixelColor = Color.FromArgb(nData[3], nData[0], nData[1], nData[2]);
            pixelImage.Dispose ();

            return pixelColor;
        }

Usage Example

Example #1
2
        public static void Remove(int colour, ref Bitmap bp)
        {
            Color c;
              switch (colour)
              {
            case BLUE:
              for (int i = 1; i < bp.Width; i++)
            for (int j = 1; j < bp.Height; j++)
            {
              c = bp.GetPixel(i, j);
              bp.SetPixel(i, j, Color.FromArgb(c.R, c.G, 0));
            }
              break;

            case RED:
              for (int i = 1; i < bp.Width; i++)
            for (int j = 1; j < bp.Height; j++)
            {
              c = bp.GetPixel(i, j);
              bp.SetPixel(i, j, Color.FromArgb(0, c.G, c.B));
            }
              break;

            case GREEN:
              for (int i = 1; i < bp.Width; i++)
            for (int j = 1; j < bp.Height; j++)
            {
              c = bp.GetPixel(i, j);
              bp.SetPixel(i, j, Color.FromArgb(c.R, 0, c.B));
            }
              break;
              }
        }
All Usage Examples Of System.Drawing.Bitmap::GetPixel