Java Image to BufferedImage toGrayBufferedImage(Image image)

Here you can find the source of toGrayBufferedImage(Image image)

Description

Converts an AWT Image into a gray scale BufferedImage.

License

Open Source License

Parameter

Parameter Description
image the image to convert

Return

a BufferedImage

Declaration

public static BufferedImage toGrayBufferedImage(Image image) 

Method Source Code


//package com.java2s;
/*//from  w  w w. j  a  v  a  2 s  .  com
 * 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.
 */

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 gray scale 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

  1. toBufferedImage(Image image, int type)
  2. toBufferedImage(Image image, int x, int y)
  3. toBufferedImage(Image img)
  4. toBufferedImage(Image img)
  5. toBufferedImage2(Image image)