在Java中获取图像的宽度和高度

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

我的猜测是你得到了-1,因为宽度和高度为空。 - Johan Nordli
4个回答

4
你应该像这样做:

你应该这样做:

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

正如这篇文章所说的那样


当处理大尺寸时,它不起作用。我只得到800X600。似乎BufferedImage的参数WritableRasterByteInterleavedRaster,它具有maxXmaxY - blackdog

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

避免使用Apache Commons Imaging!它缺少基本功能。不支持.webp格式。关于此功能的请求自2011年以来仍未实现:https://issues.apache.org/jira/browse/IMAGING-57 - JRr

0

为什么在你的情况下会发生这种情况还不清楚,因为你没有明确指定image实际上是什么。

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

public abstract int getWidth(ImageObserver observer)

确定图像的宽度。如果尚未知道宽度,则此方法返回-1,并稍后通知指定的ImageObserver对象。 显然,无法立即确定所涉及的图像的宽度和高度。您需要传递一个ImageObserver实例,该实例将在高度和宽度可以解析时调用this方法。

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

这一切都建立在图像不为空的假设之上。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接