且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

调整图像大小以适合JLabel

更新时间:2022-11-02 14:24:07

BufferedImage img = ImageIO.read(...);
Image scaled = img.getScaledInstance(500, 500, Image.SCALE_SMOOTH);
ImageIcon icon = new ImageIcon(scaled);

请注意,这会缩放图像以使其为正方形。看看 Java:维护JPanel背景的宽高比图像讨论了在缩放时保持图像的纵横比。

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.

此外,您应该阅读 Image.getScaledInstance()的危险并查看自动将ImageIcon缩放到标签大小,使用除法和conqure scaling algorithim和调整后的图像质量非常低 - - Java ,它展示了做一步规模的问题......

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...