How can I pixelate JPG with Java?
•
Java
I'm trying to pixelate JPEG using java 6 and I don't have much luck It needs to work with Java - not an image processor like Photoshop, it needs to look like an old school - like this:
Who can help me?
Solution
Using Java awt. Image (Javadoc) and javax Imageio (Javadoc) API, you can easily traverse the pixels of an image and perform pixelation yourself
The example code is as follows You need at least these imports: javax imageio. ImageIO,java. awt. image. BufferedImage,java. awt. image. Raster,java. awt. image. Writableraster and Java io. File.
Example:
// How big should the pixelations be? final int PIX_SIZE = 10; // Read the file as an Image img = ImageIO.read(new File("image.jpg")); // 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[3]; 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); // Write the new file ImageIO.write(img,"jpg",new File("image-pixelated.jpg"));
Editor: I think I should mention - as far as I know, double [] pixels are only RGB color values For example, when I dump a pixel, it looks like {204.0197.0189.0}, light tan
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码