简体   繁体   中英

Java converting image to grayscale, image won't show up

I am trying to convert an image into grayscale and output that as another image file, but when I try to run the code, nothing shows up but there's no error message. I'm not sure what is wrong. Help would be appreciated. Thank you.

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("src/image.jpg");
         image = ImageIO.read(input);
         width = image.getWidth();
         height = image.getHeight();
         for(int i=0; i<height; i++){
            for(int j=0; j<width; j++){
               Color c = new Color(image.getRGB(j, i));
               int red = (int)(c.getRed() * 0.2126);
               int green = (int)(c.getGreen() * 0.7152);
               int blue = (int)(c.getBlue() *0.0722);
               Color newColor = new Color(red+green+blue,
               red+green+blue,red+green+blue);
               image.setRGB(j,i,newColor.getRGB());
               }
          }
         File output = new File("grayscale.jpg");
         ImageIO.write(image, "jpg", output);
      } catch (Exception e) {}
   }
   static public void main(String args[]) throws Exception 
   {
      GrayScale obj = new GrayScale();
   }
}

The code is working basically. Try inserting

try 
{
    File input = new File("src/image.jpg");
    System.out.println("File exists? "+input.exists()); // THIS LINE
    ....
}
catch (Exception e) 
{
    e.printStackTrace(); // AND THIS LINE
}

Never catch an exception with an empty block in such a case!


EDIT For showing the image:

private static void showImage(final Image image)
{
    SwingUtilities.invokeLater(new Runnable()
    {
        @Override
        public void run()
        {
            JFrame f = new JFrame();
            f.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
            f.getContentPane().add(new JLabel(new ImageIcon(image)));
            f.pack();
            f.setLocationRelativeTo(null);
            f.setVisible(true);
        }
    });
}

The code works. However the newly created image grayscale.jpg is not created in the src folder where your original image resides (and probably you expect it to be created there), but in the working directory when executed. So eg in your project folder.

You just need to write this code after writing output image.

System.out.println(output.getAbsolutePath());

This will print absolute path of output file on console .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM