get Preview Image - Java 2D Graphics

Java examples for 2D Graphics:Image Convert

Description

get Preview Image

Demo Code


import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class Main{
    public static void getPreviewImage(File sourceImage, File destImage,
            String format, int WIDTH, int HEIGHT) throws Exception {
        BufferedImage simage = ImageIO.read(sourceImage);
        int x = simage.getWidth();
        int y = simage.getHeight();
        int x1 = WIDTH;
        int y1 = HEIGHT;
        if (WIDTH * y < HEIGHT * x) {
            y1 = WIDTH * y / x;/*from   w w  w.j  a  v a  2  s .co m*/
        }
        if (WIDTH * y > HEIGHT * x) {
            x1 = HEIGHT * x / y;
        }
        BufferedImage newimage = new BufferedImage(WIDTH, HEIGHT,
                BufferedImage.SCALE_SMOOTH);
        Graphics2D g = newimage.createGraphics();
        g.setColor(new Color(255, 255, 255));
        g.fillRect(0, 0, WIDTH, HEIGHT);
        Image image = simage.getScaledInstance(x1, y1,
                BufferedImage.SCALE_SMOOTH);
        g.drawImage(image, (WIDTH - x1) / 2, (HEIGHT - y1) / 2, null);
        ImageIO.write(newimage, format, destImage);
        sourceImage.delete();
    }
}

Related Tutorials