Performing a pixelation effect is a low-hanging fruit operation on a BufferedImage
.
This can be performed in two steps:
- Determine the color of the one block of the pixelation.
- Fill in the block of pixelation on the image.
Step 1: Determine the color:
public static Color determineColor(BufferedImage img, int x, int y, int w, int h) {
int cx = x + (int)(w / 2);
int cy = y + (int)(h / 2);
return new Color(img.getRGB(cx, cy), true);
}
In the determineColor
method, the pixel color from the center of the BufferedImage
is determined, and is passed back to the caller.
Step 2: Fill in the pixelation block with determined color:
BufferedImage sourceImg = ...; // Source Image.
BufferedImage destimg = ...; // Destination Image.
Graphics g = destImg.createGraphics();
int blockSize = 8;
for (int i = 0; i < sourceImg.getWidth(); i += blockSize) {
for (int j = 0; j < sourceImg.getHeight(); j += blockSize) {
Color c = determineColor(sourceImg, i, j, blockSize, blockSize);
g.setColor(c);
g.fillRect(i, j, blockSize, blockSize);
}
}
g.dispose();
Although there is quite a bit of code, this effect is intellectually a low-hanging fruit -- there isn't much complex that is going on. It is basically finding the center color of a block, and filling a box with that color. This is a fairly naive implementation, so there may be better ways to do it.
The following is a before and after comparison of performing the above pixelation effect:
