Small Java Image Resizing Utility
Another small challenge; one guy came to me with 550 photographs in around 110 folders (they represent a tree structure of content images to be delivered and browsed by a front-end web application).
The challenge was to compress and resize all the images to improve the browsing performance.
Below is the code I wrote to perform this task.
My inspiration was
http://www.mkyong.com/java/how-to-resize-an-image-in-java/ with the following small and compact code:
BufferedImage resizedImage = new BufferedImage(IMG_WIDTH, IMG_HEIGHT, type);
Graphics2D g = resizedImage.createGraphics();
g.drawImage(originalImage, 0, 0, IMG_WIDTH, IMG_HEIGHT, null);
g.dispose();
.
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ImageResize {
static int MAX_SIZE = 150;
public static void main(String[] args) throws IOException {
processFile(new File("C:\\Users\\DragosMateiS\\Desktop\\products"));
}
private static void processFile(File file) throws IOException {
if (file.isDirectory()) {
for (File child : file.listFiles())
if (child.getName().charAt(0) != '.')
processFile(child);
} else if (file.isFile()) {
BufferedImage image=ImageIO.read(file);
if (image == null)
return;
int width=image.getWidth();
int height=image.getHeight();
if(width>height){
height=MAX_SIZE*height/width;
width=MAX_SIZE;
}else{
width=MAX_SIZE*width/height;
height=MAX_SIZE;
}
BufferedImage resized = new BufferedImage(width, height, image
.getType());
Graphics2D g = resized.createGraphics();
g.drawImage(image, 0, 0, width, height, null);
g.dispose();
ImageIO.write(resized, "JPG", file);
}
}
}