Reputation: 386
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.
Upvotes: 0
Views: 1890
Reputation: 386
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
Upvotes: 1
Reputation: 205785
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.
Upvotes: 3