Pixelate an image with c#

Pixelating an image in c# is on par with blurring an image – not terribly complex. This method accepts an image, a pixelate region (rectangle), a pixelate size and returns a bitmap.

private static Bitmap Pixelate(Bitmap image, Rectangle rectangle, Int32 pixelateSize)
{
    Bitmap pixelated = new System.Drawing.Bitmap(image.Width, image.Height);

    // make an exact copy of the bitmap provided
    using (Graphics graphics = System.Drawing.Graphics.FromImage(pixelated))
        graphics.DrawImage(image, new System.Drawing.Rectangle(0, 0, image.Width, image.Height),
            new Rectangle(0, 0, image.Width, image.Height), GraphicsUnit.Pixel);

    // look at every pixel in the rectangle while making sure we're within the image bounds
    for (Int32 xx = rectangle.X; xx < rectangle.X + rectangle.Width && xx < image.Width; xx += pixelateSize)
    {
        for (Int32 yy = rectangle.Y; yy < rectangle.Y + rectangle.Height && yy < image.Height; yy += pixelateSize)
        {
            Int32 offsetX = pixelateSize / 2;
            Int32 offsetY = pixelateSize / 2;

            // make sure that the offset is within the boundry of the image
            while (xx + offsetX >= image.Width) offsetX--;
            while (yy + offsetY >= image.Height) offsetY--;

            // get the pixel color in the center of the soon to be pixelated area
            Color pixel = pixelated.GetPixel(xx + offsetX, yy + offsetY);

            // for each pixel in the pixelate size, set it to the center color
            for (Int32 x = xx; x < xx + pixelateSize && x < image.Width; x++)
                for (Int32 y = yy; y < yy + pixelateSize && y < image.Height; y++)
                    pixelated.SetPixel(x, y, pixel);
        }
    }

    return pixelated;
}

The pixelate method looks at ever block of pixels in the pixelate size, grabs the middle pixel and then sets all of the pixels in the block to that same color. If you don’t use the middle pixel, the image ends up shifting (my initial version looked at the top-left pixel.)

Dad at Christmas

Dad at Christmas

Pixelated Dad at Christmas

Pixelated Dad at Christmas

If you want to pixelate the whole image, just use the bounds of the original image as the pixelate rectangle. Here’s an example of how to overload the Pixelate() method:

private static Bitmap Pixelate(Bitmap image, Int32 blurSize)
{
    return Pixelate(image, new Rectangle(0, 0, image.Width, image.Height), blurSize);
}

Download original dad image.



Comments are closed.