簡體   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