public class ToGray {
/*二值化*/
public void binaryImage() throws IOException {
File file = new File("image/rabbit.jpeg");
BufferedImage image = ImageIO.read(file);
int width = image.getWidth();
int height = image.getHeight();
BufferedImage grayImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);// 重点,技巧在这个参数BufferedImage.TYPE_BYTE_BINARY
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int rgb = image.getRGB(i, j);
grayImage.setRGB(i, j, rgb);
}
}
File newFile = new File("image/binary_rabbit");
ImageIO.write(grayImage, "jpg", newFile);
}
/*灰度图片*/
public void grayImage() throws IOException {
File file = new File("image/rabbit.jpeg");
BufferedImage image = ImageIO.read(file);
int width = image.getWidth();
int height = image.getHeight();
BufferedImage grayImage = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_GRAY);// 重点,技巧在这个参数BufferedImage.TYPE_BYTE_GRAY
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
int rgb = image.getRGB(i, j);
grayImage.setRGB(i, j, rgb);
}
}
File newFile = new File("image/ggray_rabbit.jpg");
ImageIO.write(grayImage, "jpg", newFile);
}
public static void main(String[] args) throws IOException {
ToGray demo = new ToGray();
demo.binaryImage();
demo.grayImage();
System.out.println("hello image!");
}
}
在Eclipse之下可以正常通过,但是在IDEA下面会出现无法读取的错误,具体代码如下:
Exception in thread "main" javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1301)
at basicoperation.ToGray.grayImage(ToGray.java:70)
at basicoperation.ToGray.main(ToGray.java:93)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
at java.lang.reflect.Method.invoke(Method.java:498)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:144)
Process finished with exit code 1
请问这是怎么回事啊?
天蓬老师2017-04-24 09:15:34
@东方星痕 @捏造的信仰 ,
第一张图片是Eclipse之中的文件夹情况,第二张是IDEA里面的文件夹情况。
但是在IDEA之中,改成BufferedImage image = ImageIO.read(this.getClass().getResource((path)));就可以编译通过了,我感觉是classpath的问题或者path的问题,但具体也不太清楚。
------Update------
问题已经解决了, 原因就是,在IDEA下面,相对路径默认为Project路径或者Module路径,所以,如果要么把images文件夹和.idea文件夹同级别的目录下,或者就是放在更深层次的文件夹之中,但是要在images文件夹在创建file或者得到path的时候要把它所在的高层次的目录体现出来,这样就不会出现文件无法读取的情况了。