Bitmap.GetPixel(Int32, Int32) Method

Definition

Gets the color of the specified pixel in this Bitmap.

C#
public System.Drawing.Color GetPixel(int x, int y);

Parameters

x
Int32

The x-coordinate of the pixel to retrieve.

y
Int32

The y-coordinate of the pixel to retrieve.

Returns

A Color structure that represents the color of the specified pixel.

Exceptions

x is less than 0, or greater than or equal to Width.

-or-

y is less than 0, or greater than or equal to Height.

The operation failed.

Examples

The following code example is designed for use with Windows Forms, and it requires PaintEventArgs e, which is a parameter of the Paint event handler. The code gets the color of a pixel in a bitmap, and then fills a rectangle with that color.

C#
private void GetPixel_Example(PaintEventArgs e)
{

    // Create a Bitmap object from an image file.
    Bitmap myBitmap = new Bitmap("Grapes.jpg");

    // Get the color of a pixel within myBitmap.
    Color pixelColor = myBitmap.GetPixel(50, 50);

    // Fill a rectangle with pixelColor.
    SolidBrush pixelBrush = new SolidBrush(pixelColor);
    e.Graphics.FillRectangle(pixelBrush, 0, 0, 100, 100);
}

Applies to

Product Versions
.NET 8 (package-provided), 9 (package-provided)
.NET Framework 1.1, 2.0, 3.0, 3.5, 4.0, 4.5, 4.5.1, 4.5.2, 4.6, 4.6.1, 4.6.2, 4.7 (package-provided), 4.7, 4.7.1 (package-provided), 4.7.1, 4.7.2 (package-provided), 4.7.2, 4.8 (package-provided), 4.8, 4.8.1
.NET Standard 2.0 (package-provided)
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9