Image reading error

自作多情 提交于 2019-12-11 20:17:25

问题


I am trying to make an image writer that will read a template image and then write text on it, then create a new image with the new text. For some reason I am getting errors when my code seems fine to me. Here is the code below:

public class GUI extends JFrame{
    private JPanel p1 = new JPanel();//Puts tiles in, and organizes them for you
    private JPanel p2 = new JPanel();//Holds trash tiles
    JLabel ll = new JLabel();
    //private JPanel p3 = new JPanel();//Holds trash tiles  
    public GUI(){
        this.setTitle("Tile Game");
        this.setSize(600,600);
        this.setDefaultCloseOperation(EXIT_ON_CLOSE);
        this.setLocationRelativeTo(null);
        try {
            createTile();
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        this.add(ll);
    }   
    public void createTile() throws IOException{

        final BufferedImage image = ImageIO.read(getClass().getResource("/src/tile.png"));
        //File outPut = new File("saved.png");
        Graphics g = image.getGraphics();
        g.setFont(g.getFont().deriveFont(30f));
        g.drawString("Hello World!", 100, 100);
        g.dispose();                
        ImageIO.write(image, "png", new File("/src/test2.png"));        
        final BufferedImage image2 = ImageIO.read(new File("/src/test2.png"));  
        ImageIcon icon1 = new ImageIcon(image2);
        ll.setIcon(icon1);
        p1.add(ll); }
}

When I run the code above, I end up getting theses errors:

 GUI.<init>() line: 36  
 Start.main(String[]) line: 7   

I don't understand why I am also asked to debug the GUI constructor...It all seems to work perfectly fine to me.


回答1:


your image location is not suitable! (ignore the other classes, it's just a test project ^^)

make an folder in your eclipse project BUT NOT IN YOUR SOURCE dir (!!!) and then refer to the image like this:

Image img1 = Toolkit.getDefaultToolkit().getImage("img/index.png");


来源:https://stackoverflow.com/questions/20636425/image-reading-error

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!