我有這樣的代碼:如何從文件正確創建BufferedImage?
package test;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;
import javax.swing.WindowConstants;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
public class SwingSandbox {
public static void main(String[] args) throws IOException {
JFrame frame = buildFrame();
final BufferedImage image = ImageIO.read(new File("C:\\Projects\\Test\\src\\test\\InterestCalcGraphic.jpg"));
JPanel pane = new JPanel() {
@Override
protected void paintComponent(Graphics g) {
super.paintComponent(g);
g.drawImage(image, 0, 0, null);
}
};
frame.add(pane);
}
private static JFrame buildFrame() {
JFrame frame = new JFrame();
frame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
frame.setSize(200, 200);
frame.setVisible(true);
return frame;
}
}
當我運行它,我得到這個錯誤信息:
Exception in thread "main" javax.imageio.IIOException: Can't read input file!
at javax.imageio.ImageIO.read(ImageIO.java:1301)
at test.SwingSandbox.main(SwingSandbox.java:17)
錯誤信息讓我相信,我的文件路徑不正確,但形象存儲在我的文件目錄下的Test - src - test下。我究竟做錯了什麼?
可能的重複http://stackoverflow.com/questions/5713096/javax-imageio-iioexception-for-apparently-no-reason –
圖像無法讀取出於某種原因,也許它不存在或不支持的圖像格式 – MadProgrammer
它存在,因爲它顯示在文件目錄中,並且不支持jpgs? –