Converts an AWT Image into a grayscale BufferedImage. - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Convert

Description

Converts an AWT Image into a grayscale BufferedImage.

Demo Code

/*/*from  w w w. jav a  2 s  .  c  o 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.Graphics;

import java.awt.Image;

import java.awt.image.BufferedImage;

import javax.swing.ImageIcon;

public class Main {
    /**
     * Converts an AWT Image into a grayscale BufferedImage.
     * 
     * @param image the image to convert
     * @return a BufferedImage
     */
    public static BufferedImage toGrayBufferedImage(Image image) {
        if (image instanceof BufferedImage
                && ((BufferedImage) image).getType() == BufferedImage.TYPE_BYTE_GRAY)
            return (BufferedImage) image;

        // This code ensures that all the pixels in the image are loaded
        image = new ImageIcon(image).getImage();
        // Create a buffered image with a format that's compatible with the screen
        BufferedImage bimage = new BufferedImage(image.getWidth(null),
                image.getHeight(null), BufferedImage.TYPE_BYTE_GRAY);

        // Copy image to buffered image
        Graphics g = bimage.createGraphics();

        // Paint the image onto the buffered image
        g.drawImage(image, 0, 0, null);
        g.dispose();

        return bimage;
    }
}

Related Tutorials