6.24.2011

Image Effect : Bluring - Fast with Graphics Drawing

one of the famous effects that we can apply to images is Blur. it is used to reduce "noise" and details.
you can read here about Gaussian blur in this wiki article.

one basic blurring consist in adding to the rgb values of a pixel, all rgb values of the pixels surrounding it.
another article explaining it well, and its implementation in Visual Basic on CodeProject.

the problem - for me - is the speed. this method is slow. so after a second thought, why treating pixel by pixel? let's try blurring the hole image at the same time.

Here is what i came up with :

Sub BlurBitmap(ByRef image As Bitmap, Optional ByVal BlurForce As Integer = 1)
        'We get a graphics object from the image
        Dim g As Graphics = Graphics.FromImage(image)
        'declare an ImageAttributes to use it when drawing
        Dim att As New ImageAttributes
        'declare a ColorMatrix
        Dim m As New ColorMatrix
        ' set Matrix33 to 0.5, which represents the opacity. so the drawing will be semi-trasparent.
        m.Matrix33 = 0.5F
        'Setting this ColorMatrix to the ImageAttributes.
        att.SetColorMatrix(m)
        'drawing the image on it self, but not in the same coordinates, in a way that every pixel will be drawn on the pixels arround it.
        For x = -BlurForce To BlurForce
            For y = -BlurForce To BlurForce
                'Drawing image on it self using out ImageAttributes to draw it semi-transparent.
                g.DrawImage(image, New Rectangle(x, y, image.Width, image.Height), 0, 0, image.Width, image.Height, GraphicsUnit.Pixel, att)
            Next
        Next
        'disposing ImageAttributes and Graphics. the effect is then applied. 
        att.Dispose()
        g.Dispose()
    End Sub





Testing :
I find this way faster than treating a it pixel per pixel. try changing the value of BlurForce (which should be an integer > 0) and check the effect. have fun with it!

Any comments are very welcome.

1 comment:

GPSSteve said...

Blur works great buts still a little slow. In both the X and Y For loop I used a by step value of 8 and this improved speed a lot while still producing a satisfactory blur.