package class8_2_BlurringWithBufferedImage; import java.awt.Image; import java.awt.image.BufferedImage; import java.util.Random; /** * This {@link Filterer} blurs the image by mixing the color of each pixel * with the colors of the pixels around it. */ public class ImageBlurrer implements Filterer { private BufferedImage image; private Random generator = new Random(); public ImageBlurrer() { image = new BufferedImage(512,512,BufferedImage.TYPE_3BYTE_BGR); for(int row = 0; row < image.getHeight(); row++) { for(int col = 0; col < image.getHeight(); col++) { int rgb = 0xFF000000 | generator.nextInt(); image.setRGB(col, row, rgb); } } } @Override public Image getImage() { return image; } @Override public void doFilterStep() { final int NUM_NEIGHBORS = 8; // Offsets: final int[] colOff = {0,1,1,1,0,-1,-1,-1}; final int[] rowOff = {-1,-1,0,1,1,1,0,-1}; assert(colOff.length == NUM_NEIGHBORS); assert(rowOff.length == NUM_NEIGHBORS); final int[] neighRgb = new int[NUM_NEIGHBORS]; for(int row = 0; row < image.getHeight(); row++) { for(int col = 0; col < image.getHeight(); col++) { int numNonBorderNeighs = 0; for(int indNeigh = 0; indNeigh < NUM_NEIGHBORS; indNeigh++) { int neighRow = row+rowOff[indNeigh]; int neighCol = col+colOff[indNeigh]; if(neighRow>=0 && neighRow=0 && neighCol> 16; g += (0x0000ff00 & rgb) >> 8; b += (0x000000ff & rgb); } r/=numNonBorderNeighs; // TODO: Rounding? g/=numNonBorderNeighs; b/=numNonBorderNeighs; int rgb = 0xff000000 | (r << 16) | (g << 8) | b; image.setRGB(col, row, rgb); } } } }