Java Image Resize BufferedImage不会绘制

时间:2012-12-12 22:13:50

标签: java graphics

我正在尝试调整Image的大小,将其另存为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,但是当img是BufferedImage时,它再次使用g.drawImage(img, x, y, null);

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 个答案:

答案 0 :(得分:1)

检查:

Image imgScaled = img.getScaledInstance(width, height, Image.SCALE_SMOOTH);

如果null imgScalednull,对我而言,你有{{1}}。

忘记了哪种情况,但是有一个,当图像加载是阻塞和其他无阻塞方法时,这意味着API函数将返回并且图像尚未加载。通常需要使用观察者。就像我告诉我忘记的那样,但我遇到了那些情况!

答案 1 :(得分:1)

你有一个舍入问题......

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,这更容易处理。