Blur an image with c#

Blurring an image with c# is pretty simple. I was messing around with something one night and needed to blur certain regions of JPGs that I was processing. This method accepts an image, a blur region (rectangle), a blur size and returns a blurred bitmap.

private static Bitmap Blur(Bitmap image, Rectangle rectangle, Int32 blurSize)
{
    Bitmap blurred = new Bitmap(image.Width, image.Height);

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

    // look at every pixel in the blur rectangle
    for (Int32 xx = rectangle.X; xx < rectangle.X + rectangle.Width; xx++)
    {
        for (Int32 yy = rectangle.Y; yy < rectangle.Y + rectangle.Height; yy++)
        {
            Int32 avgR = 0, avgG = 0, avgB = 0;
            Int32 blurPixelCount = 0;

            // average the color of the red, green and blue for each pixel in the
            // blur size while making sure you don't go outside the image bounds
            for (Int32 x = xx; (x < xx + blurSize && x < image.Width); x++)
            {
                for (Int32 y = yy; (y < yy + blurSize && y < image.Height); y++)
                {
                    Color pixel = blurred.GetPixel(x, y);

                    avgR += pixel.R;
                    avgG += pixel.G;
                    avgB += pixel.B;

                    blurPixelCount++;
                }
            }

            avgR = avgR / blurPixelCount;
            avgG = avgG / blurPixelCount;
            avgB = avgB / blurPixelCount;

            // now that we know the average for the blur size, set each pixel to that color
            for (Int32 x = xx; x < xx + blurSize && x < image.Width && x < rectangle.Width; x++)
                for (Int32 y = yy; y < yy + blurSize && y < image.Height && y < rectangle.Height; y++)
                    blurred.SetPixel(x, y, Color.FromArgb(avgR, avgG, avgB));
        }
    }

    return blurred;
}

The method takes a look at every pixel within the blur rectangle and samples the reds, greens and blues within the blur size to figure out an average. Then it sets every pixel within the blur size square to the average color.

Jellyfish at the Monterey Aquarium

Jellyfish at the Monterey Aquarium

Blurred jellyfish at the Monterey Aquarium

Blurred jellyfish at the Monterey Aquarium

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

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

Download original jellyfish image.



Comments are closed.