Resizing image to fit in JLabel

前端 未结 1 1043
难免孤独
难免孤独 2020-12-07 04:38

I am trying to load an image from directory and place it as an icon in JLabel. But when the image size is big it doesn\'t fit completely in the label. I tried r

相关标签:
1条回答
  • 2020-12-07 05:02
    BufferedImage img = ImageIO.read(...);
    Image scaled = img.getScaledInstance(500, 500, Image.SCALE_SMOOTH);
    ImageIcon icon = new ImageIcon(scaled);
    

    Beware, that this will scale the image so that it is square. Take a look at Java: maintaining aspect ratio of JPanel background image which discusses maintaining the aspect ratio of the image when scaled.

    Also, you should read The Perils of Image.getScaledInstance() and have a look at Scale the ImageIcon automatically to label size which uses a divide and conqure scaling algorithim and Quality of Image after resize very low -- Java which demonstrates the issues of doing a one step scale...

    0 讨论(0)
提交回复
热议问题