使用Graphics.drawImage()缩放图像

时间:2014-11-12 13:08:24

标签: java image swing graphics

我正在创建一个2D平台游戏,我正在尝试使用我创建的自定义库来缩放图像。调用dbi.getGraphics()时,代码会给出NullPointerException。

public void scale(int width, int height) {

        JFrame tempFrame = new JFrame();
        tempFrame.setSize(source.getWidth(null), source.getHeight(null));
        Image dbi = tempFrame.createImage(source.getWidth(null), source.getHeight(null));
        Graphics dbg = dbi.getGraphics(); // NullPointerException
        dbg.drawImage(source, 0, 0, width, height, null);
        source = dbi;

        //BufferedImage temp = (BufferedImage) source;
        //temp.getScaledInstance(width, height, Image.SCALE_DEFAULT);
        //source = temp;

}

我正在使用dbi.drawImage()缩放图片。我试过了source.getGraphics().drawImage(source,0,0,width,height,null);,但它没有用。

2 个答案:

答案 0 :(得分:3)

此程序中的框架尚未显示; getGraphics()无效。而是使用BufferedImage#createGraphics(),如图所示here。另请考虑AffineTransformOphere

答案 1 :(得分:1)

我找到了一个有效的问题的答案。

int imageWidth  = source.getWidth();
        int imageHeight = source.getHeight();

        double scaleX = (double)width/imageWidth;
        double scaleY = (double)height/imageHeight;
        AffineTransform scaleTransform = AffineTransform.getScaleInstance(scaleX, scaleY);
        AffineTransformOp bilinearScaleOp = new AffineTransformOp(scaleTransform, AffineTransformOp.TYPE_BILINEAR);

        source = bilinearScaleOp.filter(
            source,
            new BufferedImage(width, height, source.getType()));

几年前我在另一个问题上找到了它。

How to improve the performance of g.drawImage() method for resizing images