Friday, January 4, 2013

read image from file, resize BufferedImage and write back the thumbnail to another file all in java code

import java.awt.Graphics;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;

/**
 *
 * @author Masoud Salehi Alamdari
 */
public class ImageResizer {

    private final Logger logger = Logger.getLogger(ImageResizer.class.getName());

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args) {
        ImageResizer imageResizer = new ImageResizer();
    }

    public ImageResizer() {
        BufferedImage image;
        try {
            image = ImageIO.read(new File("p1.jpg"));
            BufferedImage resizedImage = resize(image, 150, 150);
            ImageIO.write(resizedImage, "jpg", new File("p1_s.jpg"));
        } catch (IOException e) {
            logger.log(Level.WARNING, e.getMessage(), e);
        }
    }

    private BufferedImage resize(BufferedImage source, int width, int height) {
        BufferedImage newImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics g = newImage.getGraphics();
        g.drawImage(source.getScaledInstance(width, height, Image.SCALE_SMOOTH), 0, 0, null);
        g.dispose();
        return newImage;
    }
}

1 comment: