0

我想用图像在 eclipse 中导出我的 jar 文件。当我导出它时,程序可以工作,但是当我移动 q.jpg 时,程序失败,有什么建议吗?

public class image {
    public static void main(String[] args){
        JFrame frame = new JFrame("Collin");
        frame.setSize(500, 500);
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        frame.setResizable(false);
        ImageIcon image = new ImageIcon("path//q.jpg");
        JLabel label = new JLabel(image);
        frame.add(label);
        frame.setVisible(true);
    }
}
4

1 回答 1

1

从 Java 包中加载图像文件并不复杂。但是如果图片不是那么好,你可以将它包含在代码中。尝试下一个:

public static void main(String[] args) throws Exception {
    String encodeImage = 
    "iVBORw0KGgoAAAANSUhEUgAAABQAAAAWCAYAAADAQbwGAAAABHNCSVQICAgIfAhkiAAAAilJREFU\n" + 
    "OI2llE1IVGEUhp+Z0AhkHPpzZspGN4kmltUYYmKTJC0kkgQxzEhhIsp+sFUtomUg06IiCoICoU3K\n" + 
    "UCTE3dQmgkpoiGyMFk2CMCEtpFnYyNvCcex273UudFbf5bzn4bznHK5HkigS375/pbRkDcFAVTEp\n" + 
    "yEWcHzorl1K5UgEClJr+/P/AwaMdBaCbLosq/oYB2t/auqreky+yjTKfh1/ztnN33Il3tYWZYOUr\n" + 
    "z/7eXucip9ZP9PUUbG4HKRBTQ2mZAAX9zpNyzER2N5iWcAkkLmicnQL08NGobZ2t5cTTcd5OJhkA\n" + 
    "uH+awRY/IcIMYNBFPQDp2Yx7y9tA7xckwn6JJp0hrBvs0kuOKEtA0fgVHe7o1L2rw0Us53LqOXlc\n" + 
    "aysql5IV/iXbtGueLv2mVoCef0lJWhSg29fO2QNvjtzSoaYt2lEVVHNztCDoG70rKvN3uGer7rx+\n" + 
    "slIMenBxWC1Bjxk4cn1ImzcEJEm9bXv17M2kxcqnhazVXn5il0/1F95egA/TGcrDVQA8fvWOzn2N\n" + 
    "llnXlqxzPL2NjRFqNq03L6U9ekCAvF6vpROn+DEzI0A19fXWGRqGIUAfk0nXwGXbx7q7zcBEIuH6\n" + 
    "b2IHBNQWjZo7nJiYsAXGYjHV1dUpFAopHo87AlOplBm4nPxXWF1dLcMwNDY2Jp/PZ3KSTqctTZi+\n" + 
    "XuTnCOhgJFLUJqCfc3POQEnKzM5qMZdzhC3H1NSUslnrbf4BzetqQcm3njYAAAAASUVORK5CYII=\n";

    byte[] imageData = new sun.misc.BASE64Decoder().decodeBuffer(encodeImage);
    JLabel label = new JLabel(new ImageIcon(imageData));
    JOptionPane.showMessageDialog(null, label);
}

这并不常见,但它有效。

您可以使用以下内容将图像转换为字符串。

public static void main(String[] args) throws Exception {
    JFileChooser fileChooser = new JFileChooser();
    int option = fileChooser.showOpenDialog(null);
    if (option == JFileChooser.APPROVE_OPTION) {
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        Files.copy(Paths.get(fileChooser.getSelectedFile().toURI()), out);
        sun.misc.BASE64Encoder encoder = new sun.misc.BASE64Encoder();
        String base64Str = encoder.encode(out.toByteArray());
        System.out.println(base64Str);
    }
}
于 2013-06-27T21:07:29.863 回答