Converts a BufferedImage to the specified type. - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Convert

Description

Converts a BufferedImage to the specified type.

Demo Code

/*/*from  w  w  w .  j  av  a 2s.co  m*/
 * Image conversion utilities.
 * 
 * Copyright (c) 2006 Jean-Sebastien Senecal (js@drone.ws)
 * 
 * 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., 675 Mass
 * Ave, Cambridge, MA 02139, USA.
 */
//package com.java2s;

import java.awt.Graphics2D;

import java.awt.image.BufferedImage;

public class Main {
    /**
     * Converts a BufferedImage to the specified type.
     * 
     * @param src the source image
     * @param type the BufferedImage type
     * @return a BufferedImage with the right type
     */
    public static BufferedImage convertType(BufferedImage src, int type) {
        if (src.getType() == type)
            return src;

        int w = src.getWidth();
        int h = src.getHeight();
        BufferedImage image = new BufferedImage(w, h, type);
        Graphics2D g2 = image.createGraphics();
        g2.drawRenderedImage(src, null);
        g2.dispose();
        return image;
    }
}

Related Tutorials