调整图像大小以适合JLabel [英] Resizing image to fit in JLabel

查看:138
本文介绍了调整图像大小以适合JLabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试从目录加载图像并将其作为图标放在 JLabel 中。但是当图像尺寸很大时,它并不完全适合标签。我尝试调整图像大小以适应标签,但它不起作用。我可以知道我哪里出错吗?

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 resizing the image to fit in the label but its not working. May I know where I am going wrong?

JFileChooser choose=new JFileChooser();
choose.showOpenDialog(null);
File f=choose.getSelectedFile();
String filename=f.getAbsolutePath();
path.setText(filename);

ImageIcon icon=new ImageIcon(filename);
Image img=icon.getImage();
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null),   BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
g.drawImage(img,500, 500, null);
ImageIcon newIcon = new ImageIcon(bi);
image_label.setIcon(newIcon);


推荐答案

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

这篇关于调整图像大小以适合JLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆