[英]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();
如這篇文章所說
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.