Skip to content

Instantly share code, notes, and snippets.

@RustyKnight
Created January 16, 2022 02:21
Show Gist options
  • Save RustyKnight/6d587c8702c7fd2d6c2ca25fd2ece4d2 to your computer and use it in GitHub Desktop.
Save RustyKnight/6d587c8702c7fd2d6c2ca25fd2ece4d2 to your computer and use it in GitHub Desktop.
Simple example of pixelating an image
protected BufferedImage pixelate(BufferedImage source) {
// How big should the pixelations be?
final int PIX_SIZE = 16;
BufferedImage img = new BufferedImage(source.getWidth(), source.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = img.createGraphics();
g2d.drawImage(source, 0, 0, this);
g2d.dispose();
// Get the raster data (array of pixels)
Raster src = img.getData();
// Create an identically-sized output raster
WritableRaster dest = src.createCompatibleWritableRaster();
// Loop through every PIX_SIZE pixels, in both x and y directions
for (int y = 0; y < src.getHeight(); y += PIX_SIZE) {
for (int x = 0; x < src.getWidth(); x += PIX_SIZE) {
// Copy the pixel
double[] pixel = new double[4];
pixel = src.getPixel(x, y, pixel);
// "Paste" the pixel onto the surrounding PIX_SIZE by PIX_SIZE neighbors
// Also make sure that our loop never goes outside the bounds of the image
for (int yd = y; (yd < y + PIX_SIZE) && (yd < dest.getHeight()); yd++) {
for (int xd = x; (xd < x + PIX_SIZE) && (xd < dest.getWidth()); xd++) {
dest.setPixel(xd, yd, pixel);
}
}
}
}
// Save the raster back to the Image
img.setData(dest);
return img;
}
@RustyKnight
Copy link
Author

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment