create BufferedImage Thumbnail - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Create

Description

create BufferedImage Thumbnail

Demo Code

/**/* w  w w  .ja v a2 s .c o  m*/
 *   Copyright 2012 Dr. Krusche & Partner PartG
 *
 *   AMES-Web-Service is free software: you can redistribute it and/or 
 *   modify it under the terms of the GNU General Public License 
 *   as published by the Free Software Foundation, either version 3 of 
 *   the License, or (at your option) any later version.
 *
 *   AMES- Web-Service is distributed in the hope that it will be useful,
 *   but WITHOUT ANY WARRANTY; without even the implied warranty of
 *   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. 
 * 
 *  See the GNU General Public License for more details. 
 *
 *   You should have received a copy of the GNU General Public License
 *   along with this software. If not, see <http://www.gnu.org/licenses/>.
 *
 */
//package com.java2s;

import java.awt.Graphics2D;

import java.awt.RenderingHints;
import java.awt.image.BufferedImage;

public class Main {
    public static int THUMB_WIDTH = 96;
    public static int THUMB_HEIGHT = 64;

    /**
     * @param img
     * @return
     * @throws Exception
     */
    public static BufferedImage createThumbnail(BufferedImage img)
            throws Exception {

        BufferedImage thumbnail = null;
        Graphics2D g2 = null;

        /* 
         * Retrieve image dimensions
         */
        int imgHeight = img.getHeight(null);
        int imgWidth = img.getWidth(null);

        int scaledWidth = 0;
        int scaledHeight = 0;

        /* 
         * Position the image on the thumbnail
         */
        int scaledTop = 0;
        int scaledLeft = 0;

        if (imgWidth > imgHeight) {

            scaledWidth = THUMB_WIDTH;
            scaledHeight = (THUMB_HEIGHT * imgHeight) / imgWidth;

            scaledLeft = 0;
            scaledTop = (THUMB_HEIGHT - scaledHeight) / 2;

        } else {

            scaledWidth = (THUMB_WIDTH * imgWidth) / imgHeight;
            scaledHeight = THUMB_HEIGHT;

            scaledLeft = (THUMB_WIDTH - scaledWidth) / 2;
            scaledTop = 0;
        }

        BufferedImage scaledImage = new BufferedImage(scaledWidth,
                scaledHeight, BufferedImage.TYPE_INT_ARGB);

        g2 = scaledImage.createGraphics();
        g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                RenderingHints.VALUE_INTERPOLATION_BILINEAR);

        g2.drawImage(img, 0, 0, scaledWidth, scaledHeight, null);
        g2.dispose();

        thumbnail = new BufferedImage(THUMB_WIDTH, THUMB_HEIGHT,
                BufferedImage.TYPE_INT_ARGB);
        g2 = thumbnail.createGraphics();

        g2.drawImage(scaledImage, scaledLeft, scaledTop, null);
        g2.dispose();

        return thumbnail;

    }
}

Related Tutorials