繁体   English   中英

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

[英]Get Image Width and Height in 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培养箱(在我撰写本文时,Common Imaging仍然是SNAPSHOT):

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM