Can't get gray scale of an image in java

Baran SAHİN :

I have a problem with getting gray scale of a .jpg file. I am trying to create a new .jpg file as gray scaled but I am just copying the image nothing more. Here is my code:

package training01;

import java.awt.*;
import java.awt.image.BufferedImage;

import java.io.*;

import javax.imageio.ImageIO;
import javax.swing.JFrame;

public class GrayScale {
    BufferedImage image;
    int width;
    int height;
    public GrayScale() {
        try {
            File input = new File("digital_image_processing.jpg");
            image = ImageIO.read(input);
            width = image.getWidth();
            height = image.getHeight();
            for(int i = width;i < width;i++) {
                for(int j = height;j < height;j++) {
                    Color c =  new Color(image.getRGB(i, j));
                    int red = c.getRed();
                    int green = c.getGreen();
                    int blue = c.getBlue();
                    int val = (red+green+blue)/3;
                    Color temp = new Color(val,val,val);
                    image.setRGB(i, j, temp.getRGB());
                }
            }
            File output = new File("digital_image_processing1.jpg");
            ImageIO.write(image, "jpg", output);
        }catch(Exception e) {
            System.out.println(e);
        }
    }
    public static void main(String[] args) {
        GrayScale gs = new GrayScale();
    }
}
WJS :

You need to change the following. Start your i and j at 0.

      for(int i = width;i < width;i++) {  
         for(int j = height;j < height;j++) {

However, here is a faster way to do it. Write it to a new BufferedImage object that is set for gray scale.

      image = ImageIO.read(input);
      width = image.getWidth();
      height = image.getHeight();
      bwImage = new BufferedImage(width,
            height, BufferedImage.TYPE_BYTE_GRAY);
      Graphics g = bwImage.getGraphics();
            g.drawImage(image,0,0,null);

Then save the bwImage.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=370574&siteId=1