关于java输出图片
import javax.imageio.*;//for ImageIO.read
import java.awt.*;//for JFrame and JLabel etc
import java.awt.image.BufferedImage;
import javax.swing.*;//for JFrame and JLabel etc
import java.net.*;//for URL
import java.io.*;//for catch (
IOException e),File,InputStream, BufferedInputStream,and FileInputStream ect
public class HelloJava{
public static void main (String[] args){
BufferedImage image = null;
try {
// Read from a file
File sourceimage=new File("100_3823.JPG"); //图片要与HelloJava.java同在一目录下
image=ImageIO.read(sourceimage);
// Read from an input stream
// InputStream is=new BufferedInputStream(
// new FileInputStream("100_3804.JPG")); //图片要与HelloJava.java同在一目录下
// image=ImageIO.read(is);
} catch (IOException e) {
}
// Use a label to display the image
JFrame frame=new JFrame();
JLabel label=new JLabel(new ImageIcon(image));
frame.getContentPane().add(label,BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
//关闭窗口--退出调试
frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
}
}
报错如下:
Exception in thread "main"
java.lang.NullPointerException at javax.swing.ImageIcon. <init>(Unknown Source)
at HelloJava.main(HelloJava.java:25)
即 JLabel label=new JLabel(new ImageIcon(image))一句出错,怎么回事啊,应该怎么修改啊 ?
------解决方案--------------------
JLabel label=new JLabel(new ImageIcon("100_3823.JPG")); 这样是可以的。
如果不按上述办法,加个函数
File sourceimage=new File("100_3823.JPG"); //图片要与HelloJava.java同在一目录下
sourceimage.canRead(); //这个函数返回的是false!!!
image=ImageIO.read(sourceimage);
为什么?