[英]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. 但是,新创建的图像
grayscale.jpg
不会在原始图像所在的src
文件夹中创建(并且可能希望在此处创建),而在执行时会在工作目录中创建。 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
. 这将在
console
上打印输出文件的绝对路径。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.