问题描述
我正在尝试使图片适合 JLabel.我希望将图片尺寸缩小到更适合我的 Swing JPanel 的尺寸.
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.
我尝试使用 setPreferredSize 但它不起作用.
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?
推荐答案
大纲
以下是要遵循的步骤.
Outline
Here are the steps to follow.
- 将图片作为 BufferedImage 读取.
- 将 BufferedImage 的大小调整为另一个与 JLabel 大小相同的 BufferedImage.
- 从调整大小的 BufferedImage 创建一个 ImageIcon.
您不必设置 JLabel 的首选大小.将图像缩放到所需大小后,JLabel 将采用 ImageIcon 的大小.
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.
BufferedImage img = null;
try {
img = ImageIO.read(new File("strawberry.jpg"));
} catch (IOException e) {
e.printStackTrace();
}
调整缓冲图像的大小
Image dimg = img.getScaledInstance(label.getWidth(), label.getHeight(),
Image.SCALE_SMOOTH);
确保标签的宽度和高度与原始图像的宽度和高度的比例相同.换句话说,如果图片是 600 x 900 像素,则缩放到 100 X 150.否则,您的图片会失真.
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.
ImageIcon imageIcon = new ImageIcon(dimg);
这篇关于调整图片大小以适合 JLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!