Java Swing显示图片时首张图片尺寸过大 如何调整大小
Java Swing调整单张图片显示尺寸方案
你可以将需要调整大小的ImageIcon先转为Image对象,调用内置缩放方法处理后再重新封装为ImageIcon赋值给JLabel即可,具体实现如下:
核心修改代码
你只需要在第一张图片初始化后增加缩放逻辑即可,示例将第一张图按固定宽300px等比例缩放,避免拉伸变形:
image1 = new ImageIcon(getClass().getResource("IMG_20210928_221239.jpg")); // 新增缩放逻辑 Image originalImage = image1.getImage(); // 计算等比例缩放后的高度,可自行修改targetWidth为你需要的宽度 int targetWidth = 300; int targetHeight = (int) (originalImage.getHeight(null) * 1.0 / originalImage.getWidth(null) * targetWidth); // 缩放图片,最后一个参数为缩放算法,SCALE_SMOOTH优先保证画质 Image scaledImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH); // 替换为缩放后的图片 image1 = new ImageIcon(scaledImage); label1 = new JLabel(image1); add(label1);
修改后的完整可运行代码
import java.awt.*; import javax.swing.*; public class Images extends JFrame { private ImageIcon image1; private JLabel label1; private ImageIcon image2; private JLabel label2; Images() { setLayout(new FlowLayout()); image1 = new ImageIcon(getClass().getResource("IMG_20210928_221239.jpg")); // 第一张图片缩放逻辑 Image originalImage = image1.getImage(); int targetWidth = 300; int targetHeight = (int) (originalImage.getHeight(null) * 1.0 / originalImage.getWidth(null) * targetWidth); Image scaledImage = originalImage.getScaledInstance(targetWidth, targetHeight, Image.SCALE_SMOOTH); image1 = new ImageIcon(scaledImage); label1 = new JLabel(image1); add(label1); image2 = new ImageIcon(getClass().getResource("IMG_20210927_182247.jpg")); label2 = new JLabel(image2); add(label2); } public static void main (String args[]) { Images gui = new Images(); gui.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); gui.setVisible(true); gui.pack(); gui.setTitle("Image Program"); } }
缩放参数说明:如果不需要等比例缩放,直接修改
getScaledInstance的前两个参数为你需要的固定宽高即可;如果对性能要求更高,可以将Image.SCALE_SMOOTH替换为Image.SCALE_FAST。
内容的提问来源于stack exchange,提问作者RockZombie
相关产品推荐
相关产品推荐

