Resize image to the size of JLabel taken dynamically from file chooser in Swing app

1k views Asked by At

I am uploading images dynamically via file chooser but the image doesn't fit the size of the JLabel. How to resolve it?

public void image()
{

       fileChooser.setCurrentDirectory(new File("."));
fileChooser.setFileFilter(new javax.swing.filechooser.FileFilter() {
                @Override
                    public boolean accept(File f) {
      return f.getName().toLowerCase().endsWith(".jpg")|| f.isDirectory();                       
                    }
                @Override
                    public String getDescription() {
                        return "JPG Images";
                    }
                });
                int r = fileChooser.showOpenDialog(new JFrame());
                ImageIcon ico=new ImageIcon(fileChooser.getSelectedFile().getAbsolutePath());
                UpImage.setIcon(ico);
                file = fileChooser.getSelectedFile();

        try {
            fis = new FileInputStream(file);
        } catch (FileNotFoundException ex) {
    Logger.getLogger(EntryEmp.class.getName()).log(Level.SEVERE, null, ex);
        }
}
3

There are 3 answers

0
Aditya Singh On BEST ANSWER

Grab hold of the image with your JFileChooser like below:

BufferedImage image = ImageIO.read(fileChooser.getSelectedFile());  

Now calculate the width and height of your JLabel, and send it to the method resizeImage(BufferedImage image, int width, int height). The resizeImage method is coded below.

// This method resizes the BufferedImage to specified width and height.
// Returns an ImageIcon object.
private ImageIcon resizeImage(BufferedImage image, int width, int height) {

    // image - BufferedImage object of your file selected
    // width - Width of your JLabel
    // height - Height of yout JLabel

    // Creating a temporary Image of your desired size.
    BufferedImage tempImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
    Graphics2D gr = tempImg.createGraphics();

    g.drawImage(image, 0, 0, width, height, null); // Draw the selected image on the tempImage from co-ordinates (0, 0) to (width, height) of the tempImage.
    g.dispose();  // Clear resources.

    return new ImageIcon(tempImage);
}  

That's it. Now all you have to do is:

label.setIcon(image);  

Hope this helps :)

0
camickr On

but the image doesn't fit the size of the jlabel.

You can use Darryl's Stretch Icon.

You can have the image automatically scaled to fill the space available to the label. Or you can use proportional scaling to keep the image in its original x/y ratio.

1
Jan On

ImageIcon scaledImageIcon = new ImageIcon(icon.getImage().getScaledInstance(width, height, java.awt.Image.SCALE_SMOOTH));