Returns a thumbnail of the source image. - Java 2D Graphics

Java examples for 2D Graphics:Image Thumbnail

Description

Returns a thumbnail of the source image.

Demo Code

/*/*from   ww w .  j a va  2  s. com*/
 * $Id: GraphicsUtilities.java,v 1.11 2009-06-08 19:52:44 dsullivan Exp $
 *
 * Dual-licensed under LGPL (Sun and Romain Guy) and BSD (Romain Guy).
 *
 * Copyright 2005 Sun Microsystems, Inc., 4150 Network Circle,
 * Santa Clara, California 95054, U.S.A. All rights reserved.
 *
 * Copyright (c) 2006 Romain Guy <romain.guy@mac.com>
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms, with or without
 * modification, are permitted provided that the following conditions
 * are met:
 * 1. Redistributions of source code must retain the above copyright
 *    notice, this list of conditions and the following disclaimer.
 * 2. Redistributions in binary form must reproduce the above copyright
 *    notice, this list of conditions and the following disclaimer in the
 *    documentation and/or other materials provided with the distribution.
 * 3. The name of the author may not be used to endorse or promote products
 *    derived from this software without specific prior written permission.
 *
 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS'' AND ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES
 * OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED.
 * IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY DIRECT, INDIRECT,
 * INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
 * DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
 * THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
 * (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF
 * THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
 */
//package com.java2s;
import java.awt.image.BufferedImage;

import java.awt.GraphicsConfiguration;
import java.awt.Transparency;

import java.awt.GraphicsEnvironment;
import java.awt.Graphics2D;
import java.awt.RenderingHints;

public class Main {
    /**
     * Returns a thumbnail of the source image. This preserves the aspect ratio of the image. All images will
     * always be scaled to fit within the targetWidth and the taretHeight of the image. 
     * 
     * @param image image to create a thumbnail of
     * @param maxTargetWidth max width the thumbnail can be
     * @param maxTargetHeight max height the thumbnail can be
     */
    @SuppressWarnings("null")
    public static BufferedImage createRatioPreservedThumbnail(
            BufferedImage image, int maxTargetWidth, int maxTargetHeight) {
        int width = image.getWidth();
        int height = image.getHeight();

        boolean isTranslucent = image.getTransparency() != Transparency.OPAQUE;

        if (maxTargetWidth <= 0 || maxTargetHeight <= 0) {
            throw new IllegalArgumentException("newSize must"
                    + " be greater than 0");
        }

        float ratioWH = (float) width / (float) height;
        float ratioHW = (float) height / (float) width;

        BufferedImage thumb = image;
        BufferedImage temp = null;

        Graphics2D g2 = null;

        int previousWidth = width;
        int previousHeight = height;
        try {
            do {
                if (width > maxTargetWidth) {
                    width /= 2;
                    if (width < maxTargetWidth) {
                        width = maxTargetWidth;
                    }
                    height = (int) (width / ratioWH);
                } else if (height > maxTargetHeight) {
                    height /= 2;
                    if (height < maxTargetHeight) {
                        height = maxTargetHeight;
                    }
                    width = (int) (height / ratioHW);
                }

                if (temp == null || isTranslucent) {
                    try {
                        temp = createCompatibleImage(image, width, height);
                    } catch (Throwable e) {
                        temp = new BufferedImage(width, height,
                                image.getType());
                    }
                    if (g2 != null)
                        g2.dispose();
                    g2 = temp.createGraphics();
                    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                            RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                }
                g2.drawImage(thumb, 0, 0, width, height, 0, 0,
                        previousWidth, previousHeight, null);

                previousWidth = width;
                previousHeight = height;

                thumb = temp;
            } while ((width > maxTargetWidth) || (height > maxTargetHeight));
        } finally {
            temp.flush();
            g2.dispose();
            image.flush();
        }

        if (width != thumb.getWidth() || height != thumb.getHeight()) {
            try {
                temp = createCompatibleImage(thumb, width, height);
                g2 = temp.createGraphics();
                g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION,
                        RenderingHints.VALUE_INTERPOLATION_BILINEAR);
                g2.drawImage(thumb, 0, 0, width, height, 0, 0, width,
                        height, null);

                thumb = temp;
            } finally {
                g2.dispose();
                temp.flush();
            }
        }

        return thumb;
    }

    /**
     * <p>Returns a new compatible image with the same width, height and
     * transparency as the image specified as a parameter. That is, the
     * returned BufferedImage will be compatible with the graphics hardware.
     * If this method is called in a headless environment, then
     * the returned BufferedImage will be compatible with the source
     * image.</p>
     *
     * @see java.awt.Transparency
     * @see #createCompatibleImage(int, int)
     * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int)
     * @see #createCompatibleTranslucentImage(int, int)
     * @see #loadCompatibleImage(java.net.URL)
     * @see #toCompatibleImage(java.awt.image.BufferedImage)
     * @param image the reference image from which the dimension and the
     *   transparency of the new image are obtained
     * @return a new compatible <code>BufferedImage</code> with the same
     *   dimension and transparency as <code>image</code>
     */
    public static BufferedImage createCompatibleImage(BufferedImage image) {
        return createCompatibleImage(image, image.getWidth(),
                image.getHeight());
    }

    /**
     * <p>Returns a new compatible image of the specified width and height, and
     * the same transparency setting as the image specified as a parameter.
     * That is, the returned <code>BufferedImage</code> is compatible with
     * the graphics hardware. If the method is called in a headless
     * environment, then the returned BufferedImage will be compatible with
     * the source image.</p>
     *
     * @see java.awt.Transparency
     * @see #createCompatibleImage(java.awt.image.BufferedImage)
     * @see #createCompatibleImage(int, int)
     * @see #createCompatibleTranslucentImage(int, int)
     * @see #loadCompatibleImage(java.net.URL)
     * @see #toCompatibleImage(java.awt.image.BufferedImage)
     * @param width the width of the new image
     * @param height the height of the new image
     * @param image the reference image from which the transparency of the new
     *   image is obtained
     * @return a new compatible <code>BufferedImage</code> with the same
     *   transparency as <code>image</code> and the specified dimension
     */
    public static BufferedImage createCompatibleImage(BufferedImage image,
            int width, int height) {
        return isHeadless() ? new BufferedImage(width, height,
                image.getType()) : getGraphicsConfiguration()
                .createCompatibleImage(width, height,
                        image.getTransparency());
    }

    /**
     * <p>Returns a new opaque compatible image of the specified width and
     * height. That is, the returned <code>BufferedImage</code> is compatible with
     * the graphics hardware. If the method is called in a headless
     * environment, then the returned BufferedImage will be compatible with
     * the source image.</p>
     *
     * @see #createCompatibleImage(java.awt.image.BufferedImage)
     * @see #createCompatibleImage(java.awt.image.BufferedImage, int, int)
     * @see #createCompatibleTranslucentImage(int, int)
     * @see #loadCompatibleImage(java.net.URL)
     * @see #toCompatibleImage(java.awt.image.BufferedImage)
     * @param width the width of the new image
     * @param height the height of the new image
     * @return a new opaque compatible <code>BufferedImage</code> of the
     *   specified width and height
     */
    public static BufferedImage createCompatibleImage(int width, int height) {
        return isHeadless() ? new BufferedImage(width, height,
                BufferedImage.TYPE_INT_RGB) : getGraphicsConfiguration()
                .createCompatibleImage(width, height);
    }

    private static boolean isHeadless() {
        return GraphicsEnvironment.isHeadless();
    }

    private static GraphicsConfiguration getGraphicsConfiguration() {
        return GraphicsEnvironment.getLocalGraphicsEnvironment()
                .getDefaultScreenDevice().getDefaultConfiguration();
    }
}

Related Tutorials