18

I have an Image object that I would like to convert to an Icon or ImageIcon to add to a JTextPane. How would I go about doing this? (this is in JAVA)

clarification: my "Image" is an instance of the Image Object, not a File.

Primm
  • 1,347
  • 4
  • 19
  • 32

5 Answers5

45

What's wrong with new ImageIcon(Image)?

Image img = ...
ImageIcon icon = new ImageIcon(img);
Jeffrey
  • 44,417
  • 8
  • 90
  • 141
5

Add the image to your JTextPane document:

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);
Reimeus
  • 158,255
  • 15
  • 216
  • 276
0

Try this...

Toolkit t = Toolkit.getDefaultToolkit();

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

setIconImage(i);
Kumar Vivek Mitra
  • 33,294
  • 6
  • 48
  • 75
  • that wouldnt work, since i have an Image Object not an image File. I would have to save the image to a file, then read the file for that to work – Primm Aug 18 '12 at 17:18
  • Write it to a file by converting it into bytes – Kumar Vivek Mitra Aug 18 '12 at 17:19
  • i may have to do that, but that would be a very roundabout way – Primm Aug 18 '12 at 17:20
  • 1
    I think there's some misunderstanding here, unless you're actually advising to take the Image, write it out as binary, and read it back in to end up with another image instance. – sarcan Aug 18 '12 at 17:39
0
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);
Mark Taylor
  • 1,843
  • 14
  • 17
0

convert image to icon, for example set Icon to a jLable in netbeans, i use below code to make it true:

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