调整图片大小以适合JLabel [英] Resize a picture to fit a JLabel

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

问题描述

我正在努力使照片适合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();
}



调整BufferedImage的大小



Resize the BufferedImage

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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