3

我只想问如何获取图像的宽度和高度,因为这将返回 -1 的宽度和高度:

private void resizeImage(Image image){
    JLabel imageLabel = new JLabel();

    int imageWidth = image.getWidth(null);
    int imageHeight = image.getHeight(null);
    System.out.println("Width:" + imageWidth);
    System.out.println("Height:" + imageHeight);
}
4

4 回答 4

4

你应该这样做:

BufferedImage bimg = ImageIO.read(new File(filename));
int width          = bimg.getWidth();
int height         = bimg.getHeight(); 

正如这篇文章所说

于 2013-08-13T14:53:28.563 回答
3

使用Apache Commons Imaging,您可以获得具有更好性能的图像宽度和高度,而无需将整个图像读取到内存中。

下面的示例代码使用 Sanselan 0.97-incubator(我写这篇文章时,Commons Imaging 仍然是 SNAPSHOT):

final ImageInfo imageInfo = Sanselan.getImageInfo(imageData);
int imgWidth = imageInfo.getWidth();
int imgHeight = imageInfo.getHeight();
于 2017-07-31T05:22:44.300 回答
0

在您的情况下发生这种情况的确切原因尚不清楚,您没有具体说明image实际情况。

无论如何,答案可以在JavaDoc中找到:

public abstract int getWidth(ImageObserver observer)

确定图像的宽度。如果宽度未知,则此方法返回 -1 并稍后通知指定的 ImageObserver 对象。

显然无法立即确定相关图像的宽度和高度。您需要传递一个ImageObserver实例,该实例将在可以解析高度和宽度时调用此方法。

于 2013-08-13T13:44:59.540 回答
0
    public static BufferedImage resize(final Image image, final int width, final int height){
    assert image != null;
    final BufferedImage bi = new BufferedImage(width, height, image instanceof BufferedImage ? ((BufferedImage)image).getType() : BufferedImage.TYPE_INT_ARGB);
    final Graphics2D g = bi.createGraphics();
    g.drawImage(image, 0, 0, width, height, null);
    g.dispose();
    return bi;
}

上面发布的代码是调整图像大小的一种方法。通常要获取图像的宽度和高度,您可以执行以下操作:

image.getWidth(null);
image.getHeight(null);

这都是在图像不为空的假设下。

于 2013-08-13T14:46:16.320 回答