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的時候要把它所在的高層次的目錄體現出來,這樣就不會出現文件無法讀取的情況了。