缩放和绘制 BufferedImage

Scaling and drawing a BufferedImage

我有一个自定义的 JPanel,在 paintComponent 方法上有一个 @Override,它从一个成员变量中获取一个 BufferedImage 并绘制它。在我尝试缩放图像之前它工作正常。我从阅读中了解到有两种不同的方法。一种是使用 Image.getScaledInstance,另一种是使用缩放图像的尺寸创建 Graphics2D。但是,当我尝试使用这两种方法中的任何一种时,我要么得到一个完全白色的矩形,要么一无所获。我不确定我做错了什么。重写方法的代码如下。任何意见,将不胜感激。我确信这是微不足道的,但我看不到问题所在。

protected void paintComponent(Graphics g) {
    super.paintComponent(g);
    if (img != null) {
        int imageWidth = img.getWidth();
        int imageHeight = img.getHeight();
        int panelWidth = getWidth();
        int panelHeight = getHeight();

        if(imageWidth > panelWidth || imageHeight > panelHeight){
            double aspectRatio = (double)imageWidth / (double)imageHeight;
            int newWidth, newHeight;

            // rescale the height then change the width to pre
            if(imageWidth > panelWidth){
                double widthScaleFactor = (double)panelWidth / (double)imageWidth;
                newWidth = (int)(widthScaleFactor * imageWidth);
                newHeight = (int)(widthScaleFactor * imageWidth / aspectRatio);
            }else{
                double heightScaleFactor = (double)panelHeight / (double)imageHeight;
                newHeight = (int)(heightScaleFactor * imageHeight);
                newWidth = (int)(heightScaleFactor * imageHeight * aspectRatio);
            }

            //BufferedImage scaledImage = (BufferedImage)img.getScaledInstance(newWidth, newHeight, BufferedImage.SCALE_DEFAULT);
            BufferedImage scaledImage = new BufferedImage(newWidth, newHeight, img.getType());
            int x = (panelWidth - newWidth) / 2;
            int y = (panelHeight - newHeight) / 2;

            //Graphics2D g2d = (Graphics2D) g.create();
            Graphics2D g2d = scaledImage.createGraphics();
            //g2d.drawImage(scaledImage, x, y, this);
            g2d.drawImage(img, 0, 0, newWidth, newHeight, null);
            g2d.dispose();
        }else{
            int x = (getWidth() - img.getWidth()) / 2;
            int y = (getHeight() - img.getHeight()) / 2;

            Graphics2D g2d = (Graphics2D) g.create();
            g2d.drawImage(img, x, y, this);
            g2d.dispose();
        }
    } 

不确定它是否有帮助,因为您还没有发布 SSCCE,但这可能比您的代码更有效。

Image scaledImage = img.getScaledInstance(newWidth, newHeight, Image.SCALE_SMOOTH);
int x = (panelWidth - newWidth) / 2;
int y = (panelHeight - newHeight) / 2;
g.drawImage(scaledImage, x, y, this);