Java BufferedImage to Gray Scale imageToGrayscale(BufferedImage image)

Here you can find the source of imageToGrayscale(BufferedImage image)

Description

image To Grayscale

License

Open Source License

Declaration

public static BufferedImage imageToGrayscale(BufferedImage image) 

Method Source Code

//package com.java2s;
//License from project: Open Source License 

import java.awt.color.ColorSpace;
import java.awt.image.BufferedImage;
import java.awt.image.ColorConvertOp;

public class Main {
    private static final ColorConvertOp RGB_TO_GRAYSCALE = new ColorConvertOp(
            ColorSpace.getInstance(ColorSpace.CS_sRGB),
            ColorSpace.getInstance(ColorSpace.CS_GRAY), null);

    public static BufferedImage imageToGrayscale(BufferedImage image) {
        final BufferedImage grayscale;

        // return the buffered image as-is, if it is binary already
        if (image.getType() == BufferedImage.TYPE_BYTE_BINARY) {
            return image;
        } else if (image.getType() == BufferedImage.TYPE_BYTE_GRAY) {
            grayscale = image;//w w w  . j  av a  2  s .co m
        } else if (image.getType() == BufferedImage.TYPE_INT_RGB
                || image.getType() == BufferedImage.TYPE_BYTE_INDEXED) {
            grayscale = new BufferedImage(image.getWidth(),
                    image.getHeight(), BufferedImage.TYPE_BYTE_GRAY);

            // convert rgb image to grayscale
            RGB_TO_GRAYSCALE.filter(image, grayscale);
        } else {
            throw new IllegalArgumentException(String.format(
                    "illegal color space: %s", image.getColorModel()
                            .getColorSpace().getType()));
        }

        return grayscale;
    }
}

Related

  1. imageToGrayscale(BufferedImage img)
  2. gray(BufferedImage src)
  3. grayImage(BufferedImage image)
  4. byteBufferToGrayBufferedImage(ByteBuffer buffer, BufferedImage bi)