java - 在 swing 中调整图像大小

标签 java swing graphics bufferedimage imageicon

我有一段代码用于将图像大小调整为窗帘大小(我想将分辨率更改为 200 dpi 之类的东西)。基本上我需要它的原因是因为我想显示用户选择的图像(有点大)然后如果用户同意我想在不同的地方显示相同的图像但使用较小的分辨率。不幸的是,如果我给它一个大图像,屏幕上什么也不会出现。另外,如果我改变

imageLabel.setIcon(newIcon); 

imageLabel.setIcon(icon); 

我得到了要显示的图像,但不是以正确的分辨率显示,这就是我如何知道我在这个代码片段中有问题,而不是在其他地方。

Image img = icon.getImage();

BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
BufferedImage bi = new BufferedImage(img.getWidth(null), img.getHeight(null), BufferedImage.TYPE_INT_ARGB);
Graphics g = bi.createGraphics();
boolean myBool = g.drawImage(img, 0, 0, 100, 100, null);
System.out.println(myBool);
ImageIcon newIcon = new ImageIcon(bi);
imageLabel.setIcon(newIcon);
submitText.setText(currentImagePath);
imageThirdPanel.add(imageLabel);

最佳答案

您真的不必关心缩放图像的细节。 Image 类已经有一个方法 getScaledInstance(int width, int height, int hints) 专为此目的而设计。 Java 文档说:

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. If either the width or height is a negative number then a value is substituted to maintain the aspect ratio of the original image dimensions.

你可以这样使用它:

// Scale Down the original image fast
Image scaledImage = imageToScale.getScaledInstance(newWidth, newHighth, Image.SCALE_FAST);
// Repaint this component
repaint();

检查 this一个完整的例子。

关于java - 在 swing 中调整图像大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8284048/

相关文章:

java - 什么是用于词性标记的好的 Java 库?

swing - GridBagLayout 多按钮+边框

java - 一个 Swing 组件可以在不同的行上显示单独的、可选择的字符串?

java - OneSignal 通知显示在屏幕上

java - Android App WIDGET - 语音识别器

java - Java中如何读取特定行

java - 在 JTextFields 中从法语切换为阿拉伯语

c++ - Qt4.8 QGraphicsWidget使用

c - 更好地控制 OpenGL 中的曲面 segmentation ?

C++ 成员函数指针用例?