我正在尝试调整图像大小,并将其保存为 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;
}
这里的以下方法不起作用,它需要一个文件名和一个调整大小宽度。它调整它的大小,然后将其转换为 BufferedImage,但再次使用 g.drawImage(img, x, y, null);
不起作用,其中 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;
}
所以我的问题是,为什么第二个 block 不起作用?
最佳答案
您遇到舍入问题...
Java 将根据您提供的值返回除法结果...
例如...
int width = 100;
int w = 5;
int result = width / w
// result = 0, but it should be 0.5
Java 已完成内部转换,将值转换回 int
,这只是截断十进制值。
相反,您需要鼓励 Java 以十进制值形式返回结果...
int result = width / (float)w
// result = 0.5
所以,你的缩放计算int height = (int)(h * (width/w))
实际上返回0
我会使用更多的计算
int height = Math.round((h * (width / (float)w)))
抱歉,我不太记得所有这些的“技术”废话,但这是这个想法的一般笑话;)
已更新
ImageIcon
使用后台线程实际加载图像像素,但在调用构造函数后立即返回。这意味着图像数据可能在未来一段时间内不可用。
改用ImageIO.read(new File(filename))
。这将阻塞,直到图像数据被读取并返回一个 BufferedImage
,这明显更容易处理。
关于Java Image Resize BufferedImage 不绘制,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13849603/