Set Label in Java to Image-Format Issue

走远了吗. 提交于 2021-02-05 08:07:43

问题


I am trying to set the label in a java program to an image. It seems, however, that it does not work for .bmp images

I am looking for a converter which will allow me to convert an image from a .bmp to a .jpg with the same file name. This converter needs to be controlled by the java program, which has the name and location of the image that needs to be converted.

Any help would be greatly appreciated as I have spent hours on this :P

Thanks

*Edit: The program needs to be able to be packaged with the program so that it can work on multiple computers (ie cannot be something that I install to my computer). I'm hoping to find a .exe which recieves the image file name as a parameter and converts it to .jpg


回答1:


Use ImageIO#read Like so (java 1.4 and up):

ImageIcon icon = new ImageIcon(ImageIO.read(filename));

JLabel label = new JLabel(icon);

For anything below Java 1.4 use image4j

UPDATE:

Here is an example I made:

enter image description here

import java.awt.Dimension;
import java.awt.Image;
import java.io.IOException;
import java.net.MalformedURLException;
import java.net.URL;
import javax.imageio.ImageIO;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.SwingUtilities;

public class JLabelBmpTest {

    public JLabelBmpTest() throws  MalformedURLException, IOException {
        initComponents();
    }

    public static void main(String[] args) {
        SwingUtilities.invokeLater(new Runnable() {
            @Override
            public void run() {
                try {
                    new JLabelBmpTest();
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        });
    }

    private void initComponents() throws MalformedURLException, IOException {
        JFrame frame = new JFrame();
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        Image background = ImageIO.read(new URL("http://www.3drealms.com/zerohour/images/zhbackground.bmp"));
        final ImageIcon ii = new ImageIcon(background);

        frame.add(new JLabel(ii) {
            @Override
            public Dimension getPreferredSize() {
                return new Dimension(ii.getIconWidth(), ii.getIconHeight());

            }
        });

        frame.setResizable(false);
        frame.pack();
        frame.setVisible(true);
    }
}

Reference:

  • Display BMP in JLabel


来源:https://stackoverflow.com/questions/12982264/set-label-in-java-to-image-format-issue

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