title: Java: implementation of Gaussian Blur
body: <p>I need to implement Gaussian Blur in Java for 3x3, 5x5 and 7x7 matrix. Can you correct me if I'm wrong:</p>
  
  <ol>
  <li><p>I've a matrix(M) 3x3 (middle value is M(0, 0)):  </p>
  
  <pre><code>1 2 1  
  2 4 2  
  1 2 1  
  </code></pre></li>
  <li><p>I take one pixel(P) from image and for each nearest pixel:</p>
  
  <pre><code>s = M(-1, -1) * P(-1, -1) + M(-1, 0) * P(-1, 0) + ... + M(1, 1) * P(1, 1)  
  </code></pre></li>
  <li><p>An then division it total value of matrix:</p>
  
  <pre><code>P'(i, j) = s / M(-1, -1) + M(-1, 0) + ... + M(1, 1)
  </code></pre></li>
  </ol>
  
  <p>That's all that my program do. I leave extreme pixels not changed.</p>
  
  <p>My program:  </p>
  
  <pre><code>for(int i = 1; i &lt; height - 1; i++){  
      for(int j = 1; j &lt; width - 1; j++){  
          int sum = 0, l = 0;
          for(int m = -1; m &lt;= 1; m++){  
              for(int n = -1; n &lt;= 1; n++){  
                  try{  
                      System.out.print(l + " ");  
                      sum += mask3[l++] * Byte.toUnsignedInt((byte) source[(i + m) * height + j + n]);  
                  } catch(ArrayIndexOutOfBoundsException e){  
                      int ii = (i + m) * height, jj = j + n;  
                      System.out.println("Pixels[" + ii + "][" + jj + "]    " + i + ", " + j);  
                      System.exit(0);  
                  }  
              }  
              System.out.println();  
          }  
          System.out.println();  
          output[i * width + j] = sum / maskSum[0];  
      }  
  }
  </code></pre>
  
  <hr>
  
  <p>I get <code>source</code> from a <code>BufferedImage</code> like this:</p>
  
  <pre><code>int[] source = image.getRGB(0, 0, width, height, null, 0, width);
  </code></pre>
  
  <p>So for this image:
  <a href="https://i.stack.imgur.com/PSgQs.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/PSgQs.png" alt="Picture before"></a></p>
  
  <p>Result is this:
  <a href="https://i.stack.imgur.com/TYjua.png" rel="nofollow noreferrer"><img src="https://i.stack.imgur.com/TYjua.png" alt="Picture after"></a></p>
  
  <p>Can you describe me, <strong>what is wrong with my program?</strong></p>