Improve company productivity with a Business Account.Sign Up

x
?
Solved

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

Posted on 2013-01-20
5
Medium Priority
?
2,475 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 17

Expert Comment

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

Accepted Solution

by:
CEHJ earned 1500 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 17

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

The 14th Annual Expert Award Winners

The results are in! Meet the top members of our 2017 Expert Awards. Congratulations to all who qualified!

Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Introduction This article is the second of three articles that explain why and how the Experts Exchange QA Team does test automation for our web site. This article covers the basic installation and configuration of the test automation tools used by…
A discussion about automated testing of Web Applications utilizing Selenium, along with illustrated configuration steps for the Jenkins open source tool.
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…
How to fix incompatible JVM issue while installing Eclipse While installing Eclipse in windows, got one error like above and unable to proceed with the installation. This video describes how to successfully install Eclipse. How to solve incompa…

589 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