Resize a picture to fit a JLabel

后端 未结 8 575
不思量自难忘°
不思量自难忘° 2020-11-29 01:56

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 setPreferredSiz

8条回答
  •  余生分开走
    2020-11-29 02:21

    Outline

    Here are the steps to follow.

    • Read the picture as a BufferedImage.
    • Resize the BufferedImage to another BufferedImage that's the size of the JLabel.
    • Create an ImageIcon from the resized BufferedImage.

    You do not have to set the preferred size of the JLabel. Once you've scaled the image to the size you want, the JLabel will take the size of the ImageIcon.

    Read the picture as a BufferedImage

    BufferedImage img = null;
    try {
        img = ImageIO.read(new File("strawberry.jpg"));
    } catch (IOException e) {
        e.printStackTrace();
    }
    

    Resize the BufferedImage

    Image dimg = img.getScaledInstance(label.getWidth(), label.getHeight(),
            Image.SCALE_SMOOTH);
    

    Make sure that the label width and height are the same proportions as the original image width and height. In other words, if the picture is 600 x 900 pixels, scale to 100 X 150. Otherwise, your picture will be distorted.

    Create an ImageIcon

    ImageIcon imageIcon = new ImageIcon(dimg);
    

提交回复
热议问题