create BufferedImage Source - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Create

Description

create BufferedImage Source

Demo Code

/**/*  ww  w.jav  a2s .  c om*/
 *   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 PRE_HEIGHT = 480;
    public static int SRC_WIDTH = 200;
    public static int SRC_HEIGHT = 200;

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

        BufferedImage source = 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 background
         */
        int scaledTop = 0;
        int scaledLeft = 0;

        if (imgWidth > imgHeight) {

            scaledWidth = SRC_WIDTH;
            scaledHeight = (SRC_HEIGHT * imgHeight) / imgWidth;

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

        } else {

            scaledWidth = (SRC_WIDTH * imgWidth) / imgHeight;
            scaledHeight = PRE_HEIGHT;

            scaledLeft = (SRC_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();

        source = new BufferedImage(SRC_WIDTH, SRC_HEIGHT,
                BufferedImage.TYPE_INT_ARGB);
        g2 = source.createGraphics();

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

        return source;

    }
}

Related Tutorials