简体   繁体   English

使用 BufferedImage 将图像加载到 Java 中 - Oracle 教程

[英]Load Image into Java with BufferedImage - Oracle tutorial

I'm a beginner in Java and I would like to load an image with this script:我是 Java 初学者,我想使用此脚本加载图像:

import java.awt.*;
import java.awt.event.*;
import java.awt.image.*;
import java.io.*;
import javax.imageio.*;
import javax.swing.*;

/**
 * This class demonstrates how to load an Image from an external file
 */
public class LoadImageApp extends Component {

BufferedImage img;

public void paint(Graphics g) {
    g.drawImage(img, 0, 0, null);
}

public LoadImageApp() {
   try {
       img = ImageIO.read(getClass().getResource("/resources/java.png"));//cannot found image
   } catch (IOException e) {
   }

}

public Dimension getPreferredSize() {
    if (img == null) {
         return new Dimension(100,100);
    } else {
       return new Dimension(img.getWidth(null), img.getHeight(null));
   }
}

public static void main(String[] args) {

    JFrame f = new JFrame("Load Image Sample");

    f.addWindowListener(new WindowAdapter(){
            public void windowClosing(WindowEvent e) {
                System.exit(0);
            }
        });

    f.add(new LoadImageApp());
    f.pack();
    f.setVisible(true);
}
}

Then I put a picture on a folder resource "resources", change the name of the location of the picture like "/resources/java.png" and when I compile, there is an empty window without image.然后我在文件夹资源“resources”上放了一张图片,将图片位置的名称更改为“/resources/java.png”,当我编译时,有一个没有图像的空窗口。

You can see error here : https://ibb.co/ysjNyQw你可以在这里看到错误: https : //ibb.co/ysjNyQw

The first thing you're going to want to do is do some research into "embedded resources", for example你会想要做的第一件事是做一些研究“嵌入的资源”, 例如

I don't use Eclipse, I use Netbeans, but the process should be the same我不使用Eclipse,我使用Netbeans,但过程应该是一样的

项目

As you can see, I've placed my image in the resources package within the projects "sources".如您所见,我已将我的图像放在项目“源”中的resources包中。 This will ensure that it's available at runtime via the class path search mechanism (and embedded within the resulting Jar file when I export it).这将确保它在运行时通过类路径搜索机制可用(并在我导出它时嵌入到生成的 Jar 文件中)。

I then used a JLabel to display it...然后我使用JLabel来显示它...

示例图像

import java.awt.Dimension;
import java.awt.EventQueue;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

public class Test {

    public static void main(String[] args) {
        new Test();
    }

    public Test() {
        EventQueue.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    try {
                        UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
                    } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
                        ex.printStackTrace();
                    }

                    BufferedImage image = ImageIO.read(getClass().getResource("/resources/java.png"));
                    JLabel label = new JLabel(new ImageIcon(image));

                    JFrame frame = new JFrame("Testing");
                    frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
                    frame.add(label);
                    frame.pack();
                    frame.setLocationRelativeTo(null);
                    frame.setVisible(true);
                } catch (IOException ex) {
                    Logger.getLogger(Test.class.getName()).log(Level.SEVERE, null, ex);
                }
            }
        });
    }
}

Now, if you want to continue using a custom painting route, I suggest having a read of:现在,如果您想继续使用自定义绘画路线,我建议您阅读以下内容:

to get a better understanding of how painting works in Swing and how you should work with it更好地了解绘画在 Swing 中的工作原理以及您应该如何使用它

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM