画像のサイズを変更しようとしています。BufferedImageとして保存します。画像を拡大縮小しなくても問題なく動作します。
次のコードでは、ファイル名が渡され、BufferedImageに変換されます。これは正常に機能しますg.drawImage(img, x, y, null);
。ここで、imgはBufferedImageです。
public Sprite(String filename){
ImageIcon imgIcon = new ImageIcon(filename);
int width = imgIcon.getIconWidth();
int height = imgIcon.getIconHeight();
BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics bg = bimg.getGraphics();
bg.drawImage(imgIcon.getImage(), 0, 0, null);
bg.dispose();
this.sprite = bimg;
}
ここでの次の方法は機能しません。ファイル名とサイズ変更幅が必要です。g.drawImage(img, x, y, null);
サイズを変更してからBufferedImageに変換しますが、imgがBufferedImageである場合は再度使用しても機能しません。
public Sprite(String filename, int width){
ImageIcon imgIcon = new ImageIcon(filename);
Image img = imgIcon.getImage();
float h = (float)img.getHeight(null);
float w = (float)img.getWidth(null);
int height = (int)(h * (width / w));
Image imgScaled = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage bimg = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
Graphics bg = bimg.getGraphics();
bg.drawImage(imgScaled, 0, 0, null);
bg.dispose();
this.sprite = bimg;
}
だから私の質問は、なぜ2番目のブロックが機能しないのですか?