在秋千中调整图像大小

Pau*_*ar. 5 java graphics swing bufferedimage imageicon

我有一段代码,我正在使用它来调整图像大小到窗帘大小(我想将分辨率更改为200 dpi).基本上我需要它的原因是因为我想显示用户选择的图像(有点大)然后如果用户批准我想在不同的地方显示相同的图像但使用较小的分辨率.不幸的是,如果我给它一个大图像,屏幕上就不会显示任何内容.另外,如果我改变了

imageLabel.setIcon(newIcon); 
Run Code Online (Sandbox Code Playgroud)

imageLabel.setIcon(icon); 
Run Code Online (Sandbox Code Playgroud)

我得到的图像显示但没有正确的分辨率,我知道我在这段代码中有问题而不是其他地方.

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);
Run Code Online (Sandbox Code Playgroud)

GET*_*Tah 9

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

创建此图像的缩放版本.返回一个新的Image对象,默认情况下将以指定的宽度和高度渲染图像.即使原始源图像已经完全加载,也可以异步加载新的Image对象.如果宽度或高度是负数,则替换值以保持原始图像尺寸的纵横比.

你可以像这样使用它:

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

请查看示例以获取完整示例.


hun*_*eox 6

这是我的解决方案:

    private BufferedImage resizeImage(BufferedImage originalImage, int width, int height, int type) throws IOException {  
        BufferedImage resizedImage = new BufferedImage(width, height, type);  
        Graphics2D g = resizedImage.createGraphics();  
        g.drawImage(originalImage, 0, 0, width, height, null);  
        g.dispose();  
        return resizedImage;  
    }  
Run Code Online (Sandbox Code Playgroud)