int[] buf;
int blurLevel;

void setup() {
  size(400,300,P3D);
  PImage img; 
  img=loadImage("Sample.jpg"); 
  image(img,0,0);

  buf=new int[width*height];
  blurLevel=1;
}

void draw() {
}

void keyPressed() {
  if (key>='1'&&key<='9') {
    blurLevel = (int)key-48;
  }

  if (key==' ') {
    loadPixels();
    for (int i=0;i<width*height;i++) { 
      buf[i]=pixels[i]; 
    }
    buf=blurBuf(buf,blurLevel);
    for (int i=0;i<width*height;i++) { 
      pixels[i]=buf[i]; 
    }
    updatePixels();
  }
}

int[] blurBuf(int[] b_in, int bL) {
  int[] b_out=new int[width*height];
  float v=1/(float)sq(1+bL*2);

  for (int y=0;y<height;y++) {
    for (int x=0;x<width;x++) {

      float rr=0, gg=0, bb=0;
      for (int yo=-bL;yo<=bL;yo++) {
        for (int xo=-bL;xo<=bL;xo++) {
          int xp=x+xo, yp=y+yo;
          // reflect:
          //if (xp<0) {xp+=width;} else if (xp>=width) {xp-=width;}
          //if (yp<0) {yp+=height;} else if (yp>=height) {yp-=height;}
          // or crop:
          if (xp<0) {
            xp=0;
          } 
          else if (xp>=width) {
            xp=width-1;
          }
          if (yp<0) {
            yp=0;
          } 
          else if (yp>=height) {
            yp=height-1;
          }

          int i=yp*width+xp;
          rr+=v*(b_in[i]>>16&255);
          gg+=v*(b_in[i]>>8&255);
          bb+=v*(b_in[i]&255);
        }
      }
      b_out[y*width+x]=int(rr)<<16|int(gg)<<8|int(bb);
    }
  }
  return b_out;
}
