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

Posted on 2013-01-20
Last Modified: 2013-01-21

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 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 {
        } catch (Exception e) {

    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.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.getContentPane().setBackground(new Color(255, 176, 0));
// 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 =; //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

Question by:AttilaB
  • 2
  • 2
LVL 16

Expert Comment

ID: 38799001
I'll have a look at your code.
LVL 86

Accepted Solution

CEHJ earned 500 total points
ID: 38799030
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.
LVL 16

Expert Comment

ID: 38799037
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));

Author Closing Comment

ID: 38799826

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:

              "C:/Documents and Settings/user/My Documents/JCreator Pro/MyProjects/TestScaleImageIcon/classes/images/image.JPG", 77, 65));

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

At least now I know what to do. Thanks.
LVL 86

Expert Comment

ID: 38800810
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])

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Title # Comments Views Activity
java  and programming certification ? 4 86
JavaScript/Java - Changing an image background color 4 56
eclipse argument 14 53
tomcat not starting 6 31
INTRODUCTION Working with files is a moderately common task in Java.  For most projects hard coding the file names, using parameters in configuration files, or using command-line arguments is sufficient.   However, when your application has vi…
Go is an acronym of golang, is a programming language developed Google in 2007. Go is a new language that is mostly in the C family, with significant input from Pascal/Modula/Oberon family. Hence Go arisen as low-level language with fast compilation…
Viewers will learn about the different types of variables in Java and how to declare them. Decide the type of variable desired: Put the keyword corresponding to the type of variable in front of the variable name: Use the equal sign to assign a v…
Viewers will learn how to properly install Eclipse with the necessary JDK, and will take a look at an introductory Java program. Download Eclipse installation zip file: Extract files from zip file: Download and install JDK 8: Open Eclipse and …

920 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now