像谷歌加一样在C#中模糊图像

时间:2015-01-07 19:05:39

标签: c# image-processing imagefilter

我正在尝试使用此代码段为我的图片添加模糊过滤器:

    public static Bitmap DoBlur(this Bitmap image, Int32 blurSize) {
        var rectangle = new Rectangle(0, 0, image.Width, image.Height);
        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;
    }

我在互联网上找到的课程。我试图将图像模糊为这样:

enter image description here

由谷歌加上作为页面封面。但最好的结果我可以得到这样的东西:

enter image description here

你可以看到我甚至没有关闭!你知道谷歌使用什么过滤器吗?或者我该如何实现?

这是我正在测试的原件:

enter image description here

2 个答案:

答案 0 :(得分:2)

主要问题是你在光源左侧和下方的像素模糊,但不是右侧和顶部。

尝试将内循环更改为:

for (Int32 x = Math.Max(0, xx - blurSize); x <= Math.Min(xx + blurSize, image.Width-1); x++) 
{
    for (Int32 y = Math.Max(0, yy - blurSize); y <= Math.Min(yy + blurSize, image.Height-1); y++) 
    {

答案 1 :(得分:-1)

我之前使用过2个插件来模糊图像:

http://nbartlomiej.github.io/foggy/

http://blurjs.com/

两者都很棒。在他们的主页上很容易遵循示例。

它们都需要调整不透明度和模糊半径以获得您想要的效果。

对我而言,您的尝试似乎缺少不透明度叠加层。