Solved

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

Posted on 2013-01-20
5
2,191 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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

Get 15 Days FREE Full-Featured Trial

Benefit from a mission critical IT monitoring with Monitis Premium or get it FREE for your entry level monitoring needs.
-Over 200,000 users
-More than 300,000 websites monitored
-Used in 197 countries
-Recommended by 98% of users

Question has a verified solution.

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

Introduction Java can be integrated with native programs using an interface called JNI(Java Native Interface). Native programs are programs which can directly run on the processor. JNI is simply a naming and calling convention so that the JVM (Java…
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…
Viewers learn about the “for” loop and how it works in Java. By comparing it to the while loop learned before, viewers can make the transition easily. You will learn about the formatting of the for loop as we write a program that prints even numbers…
Video by: Michael
Viewers learn about how to reduce the potential repetitiveness of coding in main by developing methods to perform specific tasks for their program. Additionally, objects are introduced for the purpose of learning how to call methods in Java. Define …
Suggested Courses

635 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