Solved

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

Posted on 2013-01-20
5
2,074 Views
Last Modified: 2013-01-21
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
Comment
Question by:AttilaB
  • 2
  • 2
5 Comments
 
LVL 16

Expert Comment

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

Accepted Solution

by:
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.
0
 
LVL 16

Expert Comment

by:krakatoa
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));
0
 

Author Closing Comment

by:AttilaB
ID: 38799826
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
 
LVL 86

Expert Comment

by:CEHJ
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])

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

Find Ransomware Secrets With All-Source Analysis

Ransomware has become a major concern for organizations; its prevalence has grown due to past successes achieved by threat actors. While each ransomware variant is different, we’ve seen some common tactics and trends used among the authors of the malware.

Join & Write a Comment

By the end of 1980s, object oriented programming using languages like C++, Simula69 and ObjectPascal gained momentum. It looked like programmers finally found the perfect language. C++ successfully combined the object oriented principles of Simula w…
Java Flight Recorder and Java Mission Control together create a complete tool chain to continuously collect low level and detailed runtime information enabling after-the-fact incident analysis. Java Flight Recorder is a profiling and event collectio…
Viewers will learn one way to get user input in Java. Introduce the Scanner object: Declare the variable that stores the user input: An example prompting the user for input: Methods you need to invoke in order to properly get  user input:
Viewers will learn about if statements in Java and their use The if statement: The condition required to create an if statement: Variations of if statements: An example using if statements:

708 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