Java BufferedImage to ImageIcon scaleImageToIconImage(final BufferedImage img, final int maxHeight, final int maxWidth, final boolean preserveAspectRatio, final boolean doHighQuality)

Here you can find the source of scaleImageToIconImage(final BufferedImage img, final int maxHeight, final int maxWidth, final boolean preserveAspectRatio, final boolean doHighQuality)

Description

Scales an image using a relatively fast algorithm.

License

Open Source License

Parameter

Parameter Description
imgData the byte array of the original image data (must be readable by ImageIO#read(java.io.InputStream) )
maxHeight the max height of the scaled image
maxWidth the max width of the scaled image
preserveAspectRatio if true, the scaling preserves the aspect ratio of the original image

Exception

Parameter Description
IOException an error occurred while loading the input bytes as a BufferedImage or while encoding the output as a JPEG

Return

the byte array of the scaled image

Declaration

public static ImageIcon scaleImageToIconImage(final BufferedImage img, final int maxHeight, final int maxWidth,
        final boolean preserveAspectRatio, final boolean doHighQuality) throws IOException 

Method Source Code

//package com.java2s;
/* Copyright (C) 2015, University of Kansas Center for Research
 * //from   w  ww .  j a  v  a 2  s  .co m
 * Specify Software Project, specify@ku.edu, Biodiversity Institute,
 * 1345 Jayhawk Boulevard, Lawrence, Kansas, 66045, USA
 * 
 * This program 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 2
 * of the License, or (at your option) any later version.
 * 
 * This program 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 program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
*/

import java.awt.Graphics2D;

import java.awt.RenderingHints;

import java.awt.Transparency;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import java.io.IOException;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class Main {
    /**
     * Scales an image using a relatively fast algorithm.
     * 
     * @param imgData the byte array of the original image data (must be readable by {@link ImageIO#read(java.io.InputStream)})
     * @param maxHeight the max height of the scaled image
     * @param maxWidth the max width of the scaled image
     * @param preserveAspectRatio if true, the scaling preserves the aspect ratio of the original image
     * @return the byte array of the scaled image
     * @throws IOException an error occurred while loading the input bytes as a BufferedImage or while encoding the output as a JPEG
     */
    public static ImageIcon scaleImageToIconImage(final BufferedImage img, final int maxHeight, final int maxWidth,
            final boolean preserveAspectRatio, final boolean doHighQuality) throws IOException {

        byte[] bytes = scaleImage(img, maxHeight, maxWidth, preserveAspectRatio, doHighQuality);
        if (bytes != null && bytes.length > 0) {
            return new ImageIcon(bytes);
        }
        return null;
    }

    /**
     * Scales an image using a relatively fast algorithm.
     * 
     * @param imgData the byte array of the original image data (must be readable by {@link ImageIO#read(java.io.InputStream)})
     * @param maxHeight the max height of the scaled image
     * @param maxWidth the max width of the scaled image
     * @param preserveAspectRatio if true, the scaling preserves the aspect ratio of the original image
     * @return the byte array of the scaled image
     * @throws IOException an error occurred while loading the input bytes as a BufferedImage or while encoding the output as a JPEG
     */
    public static byte[] scaleImage(final byte[] imgData, final int maxHeight, final int maxWidth,
            final boolean preserveAspectRatio, final boolean doHighQuality) throws IOException {
        ByteArrayInputStream inputStr = new ByteArrayInputStream(imgData);
        BufferedImage orig = ImageIO.read(inputStr);

        return scaleImage(orig, maxHeight, maxWidth, preserveAspectRatio, doHighQuality);
    }

    /**
     * @param orig the original image
     * @param maxHeight the max height of the scaled image
     * @param maxWidth the max width of the scaled image
     * @param preserveAspectRatio if true, the scaling preserves the aspect ratio of the original image
     * @param doHighQuality do higher quality thumbnail (slow)
     * @return the byte array of the scaled image
     * @throws IOException an error occurred while encoding the result as a JPEG image
     */
    public static byte[] scaleImage(final BufferedImage orig, final int maxHeight, final int maxWidth,
            final boolean preserveAspectRatio, boolean doHighQuality) throws IOException {
        BufferedImage scaled;
        if (true) {
            int targetW = maxWidth;
            int targetH = maxHeight;

            if (preserveAspectRatio) {
                int origWidth = orig.getWidth();
                int origHeight = orig.getHeight();

                double origRatio = (double) origWidth / (double) origHeight;
                double scaledRatio = (double) maxWidth / (double) maxHeight;

                if (origRatio > scaledRatio) {
                    targetH = (int) (targetW / origRatio);
                } else {
                    targetW = (int) (targetH * origRatio);
                }
            }

            scaled = getScaledInstance(orig, targetW, targetH, doHighQuality);
        } else {
            scaled = generateScaledImage(orig, RenderingHints.VALUE_INTERPOLATION_BILINEAR,
                    Math.max(maxHeight, maxWidth));
        }

        ByteArrayOutputStream output = new ByteArrayOutputStream(8192);

        ImageIO.write(scaled, "jpeg", output);

        byte[] outputBytes = output.toByteArray();
        output.close();

        return outputBytes;
    }

    /**
     * Convenience method that returns a scaled instance of the
     * provided {@code BufferedImage}.
     * 
     * Code stolen from http://today.java.net/pub/a/today/2007/04/03/perils-of-image-getscaledinstance.html
     *
     * @param img the original image to be scaled
     * @param targetWidth the desired width of the scaled instance,
     *    in pixels
     * @param targetHeight the desired height of the scaled instance,
     *    in pixels
     * @param hint one of the rendering hints that corresponds to
     *    {@code RenderingHints.KEY_INTERPOLATION} (e.g.
     *    {@code RenderingHints.VALUE_INTERPOLATION_NEAREST_NEIGHBOR},
     *    {@code RenderingHints.VALUE_INTERPOLATION_BILINEAR},
     *    {@code RenderingHints.VALUE_INTERPOLATION_BICUBIC})
     * @param higherQuality if true, this method will use a multi-step
     *    scaling technique that provides higher quality than the usual
     *    one-step technique (only useful in down-scaling cases, where
     *    {@code targetWidth} or {@code targetHeight} is
     *    smaller than the original dimensions, and generally only when
     *    the {@code BILINEAR} hint is specified)
     * @return a scaled version of the original {@code BufferedImage}
     */
    public static BufferedImage getScaledInstance(final BufferedImage img, final int targetWidth,
            final int targetHeight, final boolean higherQuality) {
        int type = (img.getTransparency() == Transparency.OPAQUE) ? BufferedImage.TYPE_INT_RGB
                : BufferedImage.TYPE_INT_ARGB;
        BufferedImage temp = img;

        BufferedImage result = new BufferedImage(targetWidth, targetHeight, type);
        Graphics2D g2 = result.createGraphics();
        if (higherQuality) {
            g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
        }
        g2.drawImage(temp, 0, 0, targetWidth, targetHeight, null);
        g2.dispose();

        return result;
    }

    /**
     * @param bufImg
     * @param size
     * @return
     */
    public static BufferedImage generateScaledImage(final BufferedImage bufImg,
            @SuppressWarnings("unused") final Object hintsArg, final int size) {
        BufferedImage sourceImage = bufImg;
        int srcWidth = sourceImage.getWidth();
        int srcHeight = sourceImage.getHeight();

        double longSideForSource = Math.max(srcWidth, srcHeight);
        double longSideForDest = size;

        double multiplier = longSideForDest / longSideForSource;
        int destWidth = (int) (srcWidth * multiplier);
        int destHeight = (int) (srcHeight * multiplier);

        BufferedImage destImage = null;

        destImage = new BufferedImage(destWidth, destHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D graphics2D = destImage.createGraphics();
        graphics2D.drawImage(sourceImage, 0, 0, destWidth, destHeight, null);
        graphics2D.dispose();

        return destImage;
    }
}

Related

  1. getImageIcon(BufferedImage img)
  2. getImageIcon(final BufferedImage image)
  3. toSwingImage(final BufferedImage image)