[java] Resize a picture to fit a JLabel

I'm trying to make a picture fit a JLabel. I wish to reduce the picture dimensions to something more appropriate for my Swing JPanel.

I tried with setPreferredSize but it doesn't work.

I'm wondering if there is a simple way to do it? Should I scale the image for this purpose?

This question is related to java swing jlabel

The answer is


public static void main(String s[]) 
  {

    BufferedImage image = null;
    try 
    {
        image = ImageIO.read(new File("your image path"));

    } catch (Exception e) 
    {
        e.printStackTrace();
    }

    ImageIcon imageIcon = new ImageIcon(fitimage(image, label.getWidth(), label.getHeight()));
    jLabel1.setIcon(imageIcon);
}


private Image fitimage(Image img , int w , int h)
{
    BufferedImage resizedimage = new BufferedImage(w,h,BufferedImage.TYPE_INT_RGB);
    Graphics2D g2 = resizedimage.createGraphics();
    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(img, 0, 0,w,h,null);
    g2.dispose();
    return resizedimage;
}

Assign your image to a string. Eg image Now set icon to a fixed size label.

image.setIcon(new javax.swing.ImageIcon(image.getScaledInstance(50,50,WIDTH)));

Or u can do it this way. The function u put the below 6 lines will throw an IOException. And will take your JLabel as a parameter.

BufferedImage bi=new BufferedImage(label.width(),label.height(),BufferedImage.TYPE_INT_RGB);

Graphics2D g=bi.createGraphics();

Image img=ImageIO.read(new File("path of your image"));

g.drawImage(img, 0, 0, label.width(), label.height(), null);

g.dispose();

return bi;

You can try it:

ImageIcon imageIcon = new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT));
label.setIcon(imageIcon);

Or in one line:

label.setIcon(new ImageIcon(new ImageIcon("icon.png").getImage().getScaledInstance(20, 20, Image.SCALE_DEFAULT)));

The execution time is much more faster than File and ImageIO.

I recommend you to compare the two solutions in a loop.


i have done the following and it worked perfectly

try {
        JFileChooser jfc = new JFileChooser();
        jfc.showOpenDialog(null);
        File f = jfc.getSelectedFile();
        Image bi = ImageIO.read(f);
        image1.setText("");
        image1.setIcon(new ImageIcon(bi.getScaledInstance(int width, int width, int width)));

    } catch (Exception e) {
    } 

The best and easy way for image resize using Java Swing is:

jLabel.setIcon(new ImageIcon(new javax.swing.ImageIcon(getClass().getResource("/res/image.png")).getImage().getScaledInstance(200, 50, Image.SCALE_SMOOTH)));

For better display, identify the actual height & width of image and resize based on width/height percentage


public void selectImageAndResize(){    
    int returnVal = jFileChooser.showOpenDialog(this); //open jfilechooser
    if (returnVal == jFileChooser.APPROVE_OPTION) {    //select image
        File file = jFileChooser.getSelectedFile();    //get the image
        BufferedImage bi;
        try {
            //
            //transforms selected file to buffer
            //
            bi=ImageIO.read(file);  
            ImageIcon iconimage = new ImageIcon(bi);

            //
            //get image dimensions
            //
            BufferedImage bi2 = new BufferedImage(iconimage.getIconWidth(), iconimage.getIconHeight(), BufferedImage.TYPE_INT_ARGB); 
            Graphics g = bi.createGraphics();
            iconimage.paintIcon(null, g, 0,0);
            g.dispose();

            //
            //resize image according to jlabel
            //
            BufferedImage resizedimage=resize(bi,jLabel2.getWidth(), jLabel2.getHeight()); 
            ImageIcon resizedicon=new ImageIcon(resizedimage);
            jLabel2.setIcon(resizedicon);
        } catch (Exception ex) {
            System.out.println("problem accessing file"+file.getAbsolutePath());
        }
    }
    else {
        System.out.println("File access cancelled by user.");
    }
}

Examples related to java

Under what circumstances can I call findViewById with an Options Menu / Action Bar item? How much should a function trust another function How to implement a simple scenario the OO way Two constructors How do I get some variable from another class in Java? this in equals method How to split a string in two and store it in a field How to do perspective fixing? String index out of range: 4 My eclipse won't open, i download the bundle pack it keeps saying error log

Examples related to swing

Calling another method java GUI Read input from a JOptionPane.showInputDialog box Call japplet from jframe Java JTable getting the data of the selected row What does .pack() do? How to add row of data to Jtable from values received from jtextfield and comboboxes How can I check that JButton is pressed? If the isEnable() is not work? Load arrayList data into JTable How to draw a circle with given X and Y coordinates as the middle spot of the circle? Simplest way to set image as JPanel background

Examples related to jlabel

Resize a picture to fit a JLabel Align text in JLabel to the right How to center the text in a JLabel? Swing JLabel text change on the running application Swing/Java: How to use the getText and setText string properly Java: how to add image to Jlabel? How to change the size of the font of a JLabel to take the maximum size How do I set a JLabel's background color? Newline in JLabel Multiline text in JLabel