convert BufferedImage To Gray - Java 2D Graphics

Java examples for 2D Graphics:BufferedImage Convert

Description

convert BufferedImage To Gray

Demo Code


//package com.java2s;

import java.awt.Color;

import java.awt.image.BufferedImage;

public class Main {
    public static BufferedImage convertToGray(BufferedImage bi) {
        int heightLimit = bi.getHeight();
        int widthLimit = bi.getWidth();
        BufferedImage converted = new BufferedImage(widthLimit,
                heightLimit, BufferedImage.TYPE_BYTE_GRAY);

        for (int height = 0; height < heightLimit; height++) {
            for (int width = 0; width < widthLimit; width++) {
                // Remove the alpha component
                Color c = new Color(bi.getRGB(width, height) & 0x00ffffff);
                // Normalize
                int newRed = (int) (0.2989f * c.getRed());
                int newGreen = (int) (0.5870f * c.getGreen());
                int newBlue = (int) (0.1140f * c.getBlue());
                int roOffset = newRed + newGreen + newBlue;
                converted.setRGB(width, height, roOffset);
            }/*from ww  w .j a  v a  2 s. c o  m*/
        }

        return converted;
    }
}

Related Tutorials