简体   繁体   English

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

[英]Get Image Width and Height in Java

I just want to ask how to get the width and height of an image, because this returns -1 for width and height: 我只想问一下如何获取图像的宽度和高度,因为这将返回-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);
}

You should do something like this : 您应该执行以下操作:

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

as this post says 如这篇文章所说

Exactly why this happens in your case is unclear, you don't specify exactly what image actually is. 尚不清楚这种情况发生的确切原因,您不确定确切的image是什么。

Anyway, the answer can be found in the JavaDoc : 无论如何,答案可以在JavaDoc中找到:

public abstract int getWidth(ImageObserver observer)

Determines the width of the image. 确定图像的宽度。 If the width is not yet known, this method returns -1 and the specified ImageObserver object is notified later. 如果宽度未知,则此方法返回-1,稍后将通知指定的ImageObserver对象。

The width and height obiously cannot be immediately determined for the image in question. 不能立即确定所讨论图像的宽度和高度。 You need to pass an ImageObserver instance which will have this method called when height and width can be resolved. 您需要传递一个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;
}

The code posted above is one way of resizing an image. 上面发布的代码是调整图像大小的一种方法。 Generally to get the width and height of an image, you may do: 通常,要获取图像的宽度和高度,可以执行以下操作:

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

This is all under the assumption that the image is not null. 所有这些都是在图像不为空的假设下进行的。

With Apache Commons Imaging , you can get image width and height with better performance, without reading entire image to memory. 借助Apache Commons Imaging ,您可以在不将整个图像读取到内存的情况下,以更好的性能获得图像的宽度和高度。

Sample code below is using Sanselan 0.97-incubator (Commons Imaging is still SNAPSHOT as I write this): 下面的示例代码使用的是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