将图像加载到程序(使用jar) [英] Load image to program (to work with jar)

查看:117
本文介绍了将图像加载到程序(使用jar)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想将图片加载到我的程序中,但是我的runnable jar也可以这样做。

所以 new ImageIcon(URL); JLabel 无效。

I'd like to load an image to my program, but in away that my runnable jar will also be able to do so.
So new ImageIcon(URL); to JLabel doesn't really work.

我所有的java文件都在src中文件夹,在核心包中。我想将我的照片放到src文件夹中,但在 images 包内。

All my java files are in src folder, in core package. I'd like to put my picture to src folder, but inside images package.

这是可能的,或者我必须将我的图像放到项目中的特定位置吗?

Is that possible, or do I have to put my image to specific location inside my project?

将图像加载到我的程序中以便在可运行的jar中运行的方法是什么? / p>

And what would be a way to load image into my program so it works inside a runnable jar?

推荐答案

我通常在Java Jar文件中嵌入图像的方式是我的 src中有一个包包含所有图像文件的文件夹以及一个名为资源的类。类代码类似于以下内容:

The way I usually embed imagery inside Java Jar files is I have a package in my src folder that contains all of my image files plus a single class called Resource. The class code is similar to the following:

import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.URL;

import javax.imageio.ImageIO;
import javax.swing.ImageIcon;

public class Resource{
    public static BufferedImage loadImage(String imageFileName){
        URL url = Resource.class.getResource(imageFileName);
        if(url == null) return null;

        try {
            return ImageIO.read(url);
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }

    public static ImageIcon loadIcon(String imageFileName){
        BufferedImage i = loadImage(imageFileName);
        if(i == null) return null;
        return new ImageIcon(i);
    }
}

提供资源类和所有图像文件都位于同一个包中,您只需使用 ImageIcon创建一个新的 JLabel 通过调用 loadIcon([simple filename])返回。无论您是在IDE中运行还是从Jar文件中运行,这都将起作用。

Provided the Resource class and all of your image files reside in the same package, all you have to do is create a new JLabel with the ImageIcon returned by calling loadIcon([simple filename]). This will work regardless of whether you're running in an IDE or from a Jar file.

这篇关于将图像加载到程序(使用jar)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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