繁体   English   中英

Java - 将图像转换为 Icon/ImageIcon?

[英]Java - Convert Image to Icon/ImageIcon?

我有一个 Image 对象,我想将其转换为 Icon 或 ImageIcon 以添加到 JTextPane。 我该怎么做呢? (这是在JAVA中)

澄清:我的“图像”是图像对象的实例,而不是文件。

new ImageIcon(Image)什么问题?

Image img = ...
ImageIcon icon = new ImageIcon(img);

将图像添加到 JTextPane 文档中:

Image image = ImageIO.read(new File("myImage.jpg"));

StyleContext context = new StyleContext();
StyledDocument document = new DefaultStyledDocument(context);

Style labelStyle = context.getStyle(StyleContext.DEFAULT_STYLE);

Icon icon = new ImageIcon(image);
JLabel label = new JLabel(icon);
StyleConstants.setComponent(labelStyle, label);

document.insertString(document.getLength(), "Ignored", labelStyle);

JTextPane textPane = new JTextPane(document);

试试这个...

Toolkit t = Toolkit.getDefaultToolkit();

Image i = t.getImage("icon.gif");

setIconImage(i);
ImageIcon icon=null; 

ImageIcon imageicon = new ImageIcon("C:\\Winter.jpg");

if (imageicon != null) {

    if (imageicon.getIconWidth() > 60) {
        System.out.println(jLabel1.getWidth());
        icon = new ImageIcon(imageicon.getImage().getScaledInstance(26, -1, Image.SCALE_DEFAULT));
    } else {
        icon = imageicon;
}

jLabel1.setIcon((Icon) icon);

将图像转换为图标,例如在 netbeans 中将 Icon 设置为 jLable,我使用以下代码使其成为现实:

JLabelname.setIcon(new javax.swing.ImageIcon(getClass().getResource("/slip/images/null_phot.png")));

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM