从Java中的文件读取图像时出现问题 [英] Problem reading image from a file in Java

查看:136
本文介绍了从Java中的文件读取图像时出现问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好!

我无法使用File和ImageIO从文件中读取图像

我的代码是这样的:

Hello everybody!

I have trouble reading image from a file using File and ImageIO

My code is like this:

package drawImageOnPanel;

import java.awt.*;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.JFrame;
import javax.swing.JPanel;

public class panelToDrawImageOnto extends JPanel{
	public void paintComponent(Graphics g){
		super.paintComponent(g);
		Image image = null;
		try {
		    // Read from a file
			File curDir = new File(".");
		    File file = new File(curDir, "strawberry.jpg");
		    image = ImageIO.read(file);
		    
		} catch (IOException e) {
			System.out.println("Error!");
		}
		
		g.drawImage(image, 0, 0, null);
	} 
	public static void main(String[] args)
	{
		JFrame mainWindow = new JFrame("Display image");
		mainWindow.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
		mainWindow.setVisible(true);
		mainWindow.setSize(300, 100);
		panelToDrawImageOnto imagePanel = new panelToDrawImageOnto();
		mainWindow.getContentPane().add(imagePanel);		
	}	
}



Strawberry.jpg位于panelToDrawImageOnto.java所在的同一文件夹中.但是我不断得到错误!在控制台上.这意味着我有一个IOException.有人可以告诉我!我的程序出了什么问题.我从互联网上读了一些帖子.他们没有帮助我!

任何帮助将不胜感激!



The strawberry.jpg is located in the same folder, where panelToDrawImageOnto.java is. But I constantly get the Error! on the console. This means I''ve got a IOException. Could anybody tell me please! What is wrong with my program. I''ve read some posts from internet. They don''t help me!

Any help would be appreciated!

推荐答案

没什么大不了的,我将文件夹引用省去了-可能会引起问题,并不是真正需要的.
Nothing really wrong, I would leave the folder reference out - that might cause problems and is not really needed.


这篇关于从Java中的文件读取图像时出现问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆