[英]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.