Bitmap.SetPixel(Int32, Int32, Color) Method

Definition

Sets the color of the specified pixel in this Bitmap.

C#
public void SetPixel(int x, int y, System.Drawing.Color color);

Parameters

x
Int32

The x-coordinate of the pixel to set.

y
Int32

The y-coordinate of the pixel to set.

color
Color

A Color structure that represents the color to assign to the specified pixel.

Exceptions

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 performs the following actions:

  • Creates a Bitmap.

  • Sets the color of each pixel in the bitmap to black.

  • Draws the bitmap.

C#
private void SetPixel_Example(PaintEventArgs e)
{

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

    // Draw myBitmap to the screen.
    e.Graphics.DrawImage(myBitmap, 0, 0, myBitmap.Width,
        myBitmap.Height);

    // Set each pixel in myBitmap to black.
    for (int Xcount = 0; Xcount < myBitmap.Width; Xcount++)
    {
        for (int Ycount = 0; Ycount < myBitmap.Height; Ycount++)
        {
            myBitmap.SetPixel(Xcount, Ycount, Color.Black);
        }
    }

    // Draw myBitmap to the screen again.
    e.Graphics.DrawImage(myBitmap, myBitmap.Width, 0,
        myBitmap.Width, myBitmap.Height);
}

Remarks

Use SetPixel method to set the color of an individual pixel in an image programmatically. You can also change an image programmatically by using the LockBits method. Typically for large-scale changes, the LockBits method offers better performance.

Applies to

Proizvod Verzije
.NET 8 (package-provided), 9 (package-provided), 10 (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, 4.7.1, 4.7.2, 4.8, 4.8.1
.NET Standard 2.0 (package-provided)
Windows Desktop 3.0, 3.1, 5, 6, 7, 8, 9, 10