Go Premium for a chance to win a PS4. Enter to Win

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2260
  • Last Modified:

Loading Images from File into ImageIcon of a JLabel Resized to Fit

Hi,

I was trying to load re-sized images into jLabels, and for whatever reason I cannot open
and resize the JPG files, even though I can directly load them into the jLabel
as an ImageIcon.

I made a quick test program to show what I am doing. I think this is straightforward and should work. To make it more convenient to use it in my larger program I created this method that takes the file path string argument along with the required sizes and should return an ImageIcon object to be used for setting the image for the jLabel.

What am I doing wrong here?

Any other way to do this, so that it actually works?

package testscaleimageicon;

import java.awt.Color;
import java.awt.Dimension;
import java.awt.Image;
import java.awt.Rectangle;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;

public class TestScaleImageIcon extends JFrame {
    private JLabel jLabel1 = new JLabel();
    private JLabel jLabel2 = new JLabel();
    
    // We can open file here:
    private Icon labelImage = new ImageIcon(getClass().getResource("media/image_3.JPG"));

    public TestScaleImageIcon() {
        try {
            jbInit();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void jbInit() throws Exception {
        this.getContentPane().setLayout( null );
        this.setSize( new Dimension(400, 300) );
        this.setTitle( "Test Scale Image Icon" );
        
        jLabel1.setBounds(new Rectangle(10, 55, 170, 175));
        jLabel2.setBounds(new Rectangle(245, 90, 90, 75));
        
        jLabel1.setBorder(BorderFactory.createLineBorder(Color.BLUE, 4));
        jLabel2.setBorder(BorderFactory.createLineBorder(Color.BLUE, 4));
        
        jLabel1.setIcon(labelImage);
        jLabel1.setBackground(new Color(0, 82, 255));

// Attempting to load image here, in my own method defined in this class:
        jLabel2.setIcon(getScaledImageIconFromFile("media/image_3.JPG", 77, 65));

        jLabel2.setBackground(new Color(0, 82, 255));
        this.getContentPane().add(jLabel2, null);
        this.getContentPane().add(jLabel1, null);
    }
    
    public static void main(String[] args) {
        TestScaleImageIcon testScaleImageIcon = new TestScaleImageIcon();
        testScaleImageIcon.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        testScaleImageIcon.getContentPane().setBackground(new Color(255, 176, 0));
        testScaleImageIcon.setLocationRelativeTo(null);
        testScaleImageIcon.setResizable(false);
        testScaleImageIcon.setVisible(true);
    }
    
// The method that loads and resizes image, and converts Image to ImageIcon:

    private ImageIcon getScaledImageIconFromFile(String fileNameAndPath, int width, int height) {

        //open the image from location on hard drive
        try {
            File file = new File(fileNameAndPath);
            Image image = ImageIO.read(file); //reads the image to Image object
            
            //then scale it:
            Image newimg = image.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            ImageIcon scaledImageIcon = new ImageIcon(newimg); //we now have new icon - scaled
       
            return scaledImageIcon;
            
        } catch (IOException ex) {
            System.out.println("Unable to open file: \n" + ex.getMessage()+ "\n" + ex.getStackTrace());
            JOptionPane.showMessageDialog(null, "Unable to Open File: " + fileNameAndPath,
                                          "File I/O Error", JOptionPane.WARNING_MESSAGE);
            return null;
        }
    }
}

Open in new window

image-3.JPG
TestScaleImageIcon.gif
0
AttilaB
Asked:
AttilaB
  • 2
  • 2
1 Solution
 
krakatoaCommented:
I'll have a look at your code.
0
 
CEHJCommented:
Make sure your paths are correct.
private Icon labelImage = new ImageIcon(getClass().getResource("media/image_3.JPG"));

Open in new window

should normally be
private Icon labelImage = new ImageIcon(getClass().getResource("/media/image_3.JPG"));

Open in new window

since the media directory would be at your classpath root

I also note that you've attached a file with a hyphen in the name whereas your code has one with an underscore in it.
0
 
krakatoaCommented:
Yes, looks like CEHJ has it - problem seems to be in your pathname. I ran the code with that amendment, and it renders the image in the two boxes.

So the "/" is required in your getResource call, and the pathname should be similar to :
getScaledImageIconFromFile("C:/ee_q_code/p.jpg", 77, 65));
0
 
AttilaBAuthor Commented:
Hi,

Actually it was not the full solution, but it lead me to the full solution.

You were right, it is very critical how I define path, and it is not even consistent
in Java. (The actual format of the path string seems to be inconsistent between various Java methods  and critical.)

I also got rid of the underscore or other special characters to make it simpler, and just put JPG into  <class folder>/images/image.JPG

Also, it would never work with Oracle JDeveloper IDE I was originally using. I swithed to JCreator IDE and this is what seemed to work best:

 private Icon labelImage = new ImageIcon(getClass().getResource("/images/image.JPG"));  // Relative Path will work with JCreator

or with the other image file IO method I pass down the string to:

 jLabel2.setIcon(getScaledImageIconFromFile(
              "C:/Documents and Settings/user/My Documents/JCreator Pro/MyProjects/TestScaleImageIcon/classes/images/image.JPG", 77, 65));
         // FULL PATH WILL WORK ONLY, I HAVE TO USE THIS TO WORK, IF NOT IN THE
// classes FOLDER DIRECTLY

But: NONE of these worked with Oracle JDeveloper, same 1.6 JDK.

At least now I know what to do. Thanks.
0
 
CEHJCommented:
Relative resource paths will always work, and for read-only resources, always use those over file-oriented ones. Here are the details for both major IDEs (though the principles are the same for any [or none])

http://technojeeves.com/joomla/index.php/free/126-loading-files-as-resources-in-java-with-netbeans
http://technojeeves.com/joomla/index.php/free/120-loading-files-as-resources-in-java-with-eclipse
0

Featured Post

Keep up with what's happening at Experts Exchange!

Sign up to receive Decoded, a new monthly digest with product updates, feature release info, continuing education opportunities, and more.

  • 2
  • 2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now