2014-11-12 1 views
0

2D 플랫폼 게임을 만들고 있으며 내가 만든 맞춤 라이브러리로 이미지의 크기를 조정하려고합니다. 코드는 dbi.getGraphics()을 호출 할 때 NullPointerException을 발생시킵니다.이미지가 Graphics.drawImage()로 축척되지 않습니다.

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);을 시도했지만 작동하지 않습니다.

+0

는 DBI의 null의 경우, 또는 NullPointerException이가로 getGraphics를 호출 내에서 발생되는()? 몇 줄의 스택 추적을 게시하면 여기에서 도움이됩니다. – joev

+0

@ Galen Nare 왜 Image 스케일링을 위해 Image 클래스의 getScaledInstance (width, height, hint) 메소드를 사용하지 않습니까 ?? – Muhammad

+1

@Muhammad : 어떤 위험은 [여기] (http://stackoverflow.com/a/20892645/230513)에 인용되어 있습니다. – trashgod

답변

0

나는 그 자신의 질문에 대한 답을 찾았습니다.

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

3

프레임이 프로그램의이 시점에서 표시되지 않았습니다. getGraphics()은 유효하지 않습니다. 대신 그림은 here으로 BufferedImage#createGraphics()을 사용하십시오. 또한 here으로 표시된 AffineTransformOp을 고려하십시오.

관련 문제