简体   繁体   中英

Image not scaling with Graphics.drawImage()

I am creating a 2D platformer game and am trying to scale an image with a custom library I created. The code gives a NullPointerException when invoking dbi.getGraphics() .

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;

}

I am using dbi.drawImage() to scale the image. I have tried source.getGraphics().drawImage(source,0,0,width,height,null); , but it doesn't work.

The frame has not been made visible at this point in your program; getGraphics() is invalid. Instead use BufferedImage#createGraphics() , as shown here . Also consider AffineTransformOp , seen here .

I found an answer to my own question that works.

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()));

I found it on another question from a few years ago.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM