将Java中的标签设置为图像格式问题 [英] Set Label in Java to Image-Format Issue
问题描述
我正在尝试将Java程序中的标签设置为图像.但是,它似乎不适用于.bmp图像
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
我正在寻找一个转换器,它将允许我将具有相同文件名的图像从.bmp转换为.jpg.该转换器需要由Java程序控制,该程序具有需要转换的图像的名称和位置.
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.
任何帮助,将不胜感激,因为我花了很多时间在:P
Any help would be greatly appreciated as I have spent hours on this :P
谢谢
* Edit:该程序必须能够与该程序打包在一起,以便它可以在多台计算机上运行(即不能将其安装到我的计算机上).我希望找到一个以图像文件名作为参数并将其转换为.jpg的.exe
* 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
推荐答案
使用 ImageIO#read
像这样(java 1.4及更高版本):
Use ImageIO#read
Like so (java 1.4 and up):
ImageIcon icon = new ImageIcon(ImageIO.read(filename));
JLabel label = new JLabel(icon);
对于Java 1.4以下的版本,请使用 image4j
For anything below Java 1.4 use image4j
更新:
这是我做的一个例子:
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);
}
}
参考:
这篇关于将Java中的标签设置为图像格式问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!