Convert a BufferedImage of any type, to BufferedImage of a specified type. - Java 2D Graphics

Java examples for 2D Graphics:Image Convert

Description

Convert a BufferedImage of any type, to BufferedImage of a specified type.

Demo Code

/*/*from   w  w w .  j  a va  2  s.c  o  m*/
 * JCamStream, simple Java application for video surveillance from webcams.
 * Copyright (C) 2011 Papa Issa DIAKHATE (paissad).
 * 
 * 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 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/>.
 */
//package com.java2s;
import java.awt.image.BufferedImage;

public class Main {
    /**
     * Convert a {@link BufferedImage} of any type, to {@link BufferedImage} of
     * a specified type. If the source image is the
     * same type as the target type, then original image is returned,
     * otherwise new image of the correct type is created and the content
     * of the source image is copied into the new image.
     * 
     * @param sourceImage
     *            the image to be converted
     * @param targetType
     *            the desired BufferedImage type
     * 
     * @return a BufferedImage of the specified target type.
     * 
     * @see BufferedImage
     */
    public static BufferedImage convertImageToType(
            BufferedImage sourceImage, int targetType) {
        BufferedImage image;
        if (sourceImage.getType() == targetType)
            image = sourceImage;
        else {
            image = new BufferedImage(sourceImage.getWidth(),
                    sourceImage.getHeight(), targetType);
            image.getGraphics().drawImage(sourceImage, 0, 0, null);
        }
        return image;
    }
}

Related Tutorials