In our earlier tutorials we have seen about re-sizing image, drawing image border. On same way we will see about how to convert RGB image to Grayscale image using java code. When we talk about RGB to Grayscale we can convert in lot of ways like pixel by pixel, using Java API etc., Even in our below same codes we have tried with 2 ways like using Java Graphics class and next manually reading pixel by pixel and changing the RGB values.
First lets see by using Graphics class
First lets see by using Graphics class
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class ColorToGray {
public static void main(String[] args) {
try {
File colorImage = new File("D://color.png");
File grayImage = new File("D://gray.jpg");
BufferedImage cImage = ImageIO.read(colorImage);
BufferedImage image = new BufferedImage(cImage.getWidth(), cImage.getHeight(), BufferedImage.TYPE_BYTE_GRAY);
Graphics graphics = image.getGraphics();
graphics.drawImage(cImage, 0, 0, null);
graphics.dispose();
ImageIO.write(image, "jpg", grayImage);
} catch (IOException e) {
e.printStackTrace();
}
}
}
OUTPUT:
Next we will see about reading pixel by pixel and converting RGB to Grayscale which will be time consuming but where we can play around with the pixels value which we want.
import java.awt.Color;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
public class Grayscale {
public static void main(String[] args11) throws IOException {
File colorImage = new File("D://color.jpg");
String grayImage = "D://gray.jpg";
BufferedImage cImage = ImageIO.read(colorImage);
BufferedImage gImage = new BufferedImage(cImage.getWidth(), cImage.getHeight(), cImage.getType());
for(int i=0; i<cImage.getWidth(); i++) {
for(int j=0; j<cImage.getHeight(); j++) {
int alpha = new Color(cImage.getRGB(i, j)).getAlpha();
int red = new Color(cImage.getRGB(i, j)).getRed();
int green = new Color(cImage.getRGB(i, j)).getGreen();
int blue = new Color(cImage.getRGB(i, j)).getBlue();
int gray = (red + green + blue) / 3;
red = green = blue = gray;
gray = (alpha << 24) + (red << 16) + (green << 8) + blue;
gImage.setRGB(i,j,gray);
}
}
ImageIO.write(gImage, "jpg", new File(grayImage));
}
}
OUTPUT:
INPUT FILE OUTPUT FILE
No comments:
Write comments