用Java获取图像宽度和高度

我只是想问一下如何获得图像的宽度和高度,因为这会为宽度和高度返回-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); } 

你应该做这样的事情:

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

正如这篇文章所说

究竟为什么在你的情况下发生这种情况还不清楚,你没有确切地指明实际上是什么image

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

 public abstract int getWidth(ImageObserver observer) 

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

对于所讨论的图像,不能立即确定宽度和高度。 您需要传递一个ImageObserver实例, 该实例将在解析高度和宽度时调用此方法。

  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); 

这都是在假设图像不为空的情况下进行的。

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

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

 final ImageInfo imageInfo = Sanselan.getImageInfo(imageData); int imgWidth = imageInfo.getWidth(); int imgHeight = imageInfo.getHeight();