java添加图片 标签,将Java中的标签设置为图像格式问题

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

解决方案

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:

GK9mT.png

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:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值