Java ImageIcon to BufferedImage getBufferedImageFitToWidth(ImageIcon icon, double width)

Here you can find the source of getBufferedImageFitToWidth(ImageIcon icon, double width)

Description

get Buffered Image Fit To Width

License

Open Source License

Declaration

public static BufferedImage getBufferedImageFitToWidth(ImageIcon icon, double width) 

Method Source Code

//package com.java2s;
/*//from  www .  j a  v  a  2  s  .c o m
* Jt'B Dive Logbook - Electronic dive logbook.
* 
* Copyright (C) 2010  Gautier Vanderslyen
* 
* Jt'B Dive Logbook 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.
* 
* 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, see <http://www.gnu.org/licenses/>.
*/

import java.awt.Graphics2D;

import java.awt.Image;

import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;

public class Main {
    public static BufferedImage getBufferedImageFitToWidth(ImageIcon icon, double width) {
        double originalWidth = icon.getIconWidth();
        double scale = width / originalWidth;
        return getScaledBufferedImage(icon, scale);
    }

    public static BufferedImage getScaledBufferedImage(ImageIcon icon, double scale) {
        int iw = icon.getIconWidth();
        int w = (int) (iw * scale);
        int h = (int) (icon.getIconHeight() * scale);
        BufferedImage outImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        AffineTransform trans = new AffineTransform();
        trans.scale(scale, scale);
        Graphics2D g = outImage.createGraphics();
        g.drawImage(icon.getImage(), trans, null);
        g.dispose();
        return outImage;
    }

    public static BufferedImage getScaledBufferedImage(Image icon, double scale) {
        int iw = icon.getWidth(null);
        int w = (int) (iw * scale);
        int h = (int) (icon.getHeight(null) * scale);
        BufferedImage outImage = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
        AffineTransform trans = new AffineTransform();
        trans.scale(scale, scale);
        Graphics2D g = outImage.createGraphics();
        g.drawImage(icon, trans, null);
        g.dispose();
        return outImage;
    }
}

Related

  1. getBufferedImage(final ImageIcon icon)
  2. getBufferedImage(ImageIcon icon)
  3. imageIconToBufferedImage(ImageIcon icon)
  4. imageToBufferedImage(ImageIcon src)