有人可以解释为什么这行代码不起作用。没有给出错误。它根本不会调整图像的大小。
image = ImageIO.read(file);
image.getScaledInstance(ImageDisplayBox.getWidth(), ImageDisplayBox.getHeight());
ImageDisplayBox.setIcon(new ImageIcon(image));
我查看了 Stackoverflow 上的其他答案,发现很多人使用 .getScaledInstance 方法。
我(认为)可能是因为我将它作为 .setIcon - 尽管我不是最擅长 Java 的。
图像已打印,但由于尺寸原因仅显示图像的左上角。
最佳答案
您忽略了返回值。你想要:
image = image.getScaledInstance(ImageDisplayBox.getWidth(),
ImageDisplayBox.getHeight(), 5);
或者为了让事情更清楚:
Image scaled = image.getScaledInstance(ImageDisplayBox.getWidth(),
ImageDisplayBox.getHeight(), 5);
ImageDisplayBox.setIcon(new ImageIcon(scaled));
来自 the docs :
Creates a scaled version of this image. A new Image object is returned which will render the image at the specified width and height by default. The new Image object may be loaded asynchronously even if the original source image has already been loaded completely.
请注意,这并没有说明要更改现有 图像。它只是创建一个具有给定大小的新图像。
关于java - 图像大小调整,Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10896723/