在Netbeans中阅读图像

Tha*_*wen 7 java swing bufferedimage path

我的项目中有一个图像文件.层次结构如下所示:

项目层次结构

我正在尝试使用以下代码将Manling.png读入Manling.java:

public BufferedImage sprite;

public Manling()
{
    try
    {
    File file = new File("resources/Manling.png");
    sprite = ImageIO.read(file);
    } catch (IOException e) {}

    System.out.println(sprite.toString()); //This line is to test if it works
}
Run Code Online (Sandbox Code Playgroud)

我总是得到NullPointerExceptionprintln语句,所以我假设的路径是错误的.我已经尝试将图像移动到项目中的不同位置,我尝试更改文件路径(例如'mine/resources/Manling.png'和'/resources/Manling.png').有任何想法吗?

如果您想要一个完整的可编译示例,请尝试以下方法:

package minesscce;

import javax.swing.*;
import java.awt.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import java.net.URL;

public class Mine extends JFrame
{
private BufferedImage sprite;

public static void main(String args[])
{
    Mine mine = new Mine();
}

public Mine()
{
    setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    setVisible(true);
    setSize(800, 600);
    setExtendedState(Frame.MAXIMIZED_BOTH);
    setBackground(Color.WHITE);

    try
    {
        File file = new File("resources/Manling.png");
        sprite = ImageIO.read(file);
    } catch (IOException e) {}

    System.out.println(sprite.toString());
}

public void paint(Graphics g)
{
    g.translate(getInsets().left, getInsets().top);
    Graphics2D g2d = (Graphics2D)g;

    g2d.drawImage(sprite, 0, 0, this);
    Toolkit.getDefaultToolkit().sync();
    g2d.dispose();
}
Run Code Online (Sandbox Code Playgroud)

}

只需使用您想要的任何图像设置这样的项目:

SSCCE

mre*_*mre 10

尝试

ImageIO.read(Mine.class.getResource("../minesscce.resources/Manling.png"));
Run Code Online (Sandbox Code Playgroud)

这是一个例子:

  • 等级制度

在此输入图像描述

  • 结果

在此输入图像描述

这是代码 ......

public final class ImageResourceDemo {
    private static BufferedImage bi;

    public static void main(String[] args){
        try {
            loadImage();

            SwingUtilities.invokeLater(new Runnable(){
                @Override
                public void run() {
                    createAndShowGUI();             
                }
            });
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    private static void loadImage() throws IOException{
        bi = ImageIO.read(
                ImageResourceDemo.class.getResource("../resource/avatar6.jpeg"));
    }

    private static void createAndShowGUI(){
        final JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.getContentPane().setBackground(Color.WHITE);
        frame.add(new JLabel(new ImageIcon(bi)));
        frame.pack();
        frame.setLocationRelativeTo(null);
        frame.setVisible(true);
    }
}
Run Code Online (Sandbox Code Playgroud)