爪哇 - 转换图片到图标/ ImageIcon的?(Java - Convert Image to

2019-06-27 04:12发布

我有一个图片对象,我想转换为图标或ImageIcon的添加到JTextPane中。 我将如何去这样做呢? (这是在JAVA)

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

Answer 1:

有什么不对new ImageIcon(Image)

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


Answer 2:

图像添加到您的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);


Answer 3:

试试这个...

Toolkit t = Toolkit.getDefaultToolkit();

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

setIconImage(i);


Answer 4:

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);


文章来源: Java - Convert Image to Icon/ImageIcon?