如何在java中获取图像的大小

嗨我在java中使用Jtidy解析器。


URL url = new URL("http://l1.yimg.com/t/frontpage/baba-ramdev-310511-60.jpg"); Image image = new ImageIcon(url).getImage(); int imgWidth = image.getWidth(null); int imgHeight = image.getHeight(null); 

上面的代码工作正常,我正确得到高度和宽度。但我想看到图像的大小(例如它是以KB还是以MB为单位)。请帮助我,如何获得图像的大小。有什么办法吗?

这是找到图像尺寸的最简单方法之一。

  URL url=new URL("Any web image url"); BufferedImage image = ImageIO.read(url); int height = image.getHeight(); int width = image.getWidth(); System.out.println("Height : "+ height); System.out.println("Width : "+ width); 

尝试:

 url.openConnection().getContentLength(); 

如果这不起作用,您可以使用以下命令加载流:

 url.openStream() 

…并读取流直到结束,计算实际读取的字节数。 您也可以使用CountingInputStream装饰器稍后重用该流。 但是第一个代码片段似乎有用。

如何计算你的字节并吃掉它们。

 import java.awt.Image; import javax.imageio.ImageIO; import javax.swing.*; import java.net.URL; import java.io.*; class ImageInfo { public static void main(String[] args) throws Exception { URL url = new URL( "http://l1.yimg.com/t/frontpage/baba-ramdev-310511-60.jpg"); ByteArrayOutputStream baos = new ByteArrayOutputStream(); InputStream is = url.openStream(); byte[] b = new byte[2^16]; int read = is.read(b); while (read>-1) { baos.write(b,0,read); read = is.read(b); } int countInBytes = baos.toByteArray().length; ByteArrayInputStream bais = new ByteArrayInputStream( baos.toByteArray()); Image image = ImageIO.read(bais); int width = image.getWidth(null); int height = image.getHeight(null); String imageInfo = width + "x" + height + " px, " + countInBytes + " bytes."; JOptionPane.showMessageDialog(null, new JLabel(imageInfo, new ImageIcon(image), SwingConstants.CENTER)); } } 

在此处输入图像描述

使用HEAD请求获取内容长度

 URL url = new URL("http://l1.yimg.com/t/frontpage/baba-ramdev-310511-60.jpg"); //Set the user agent System.setProperty("http.agent", "Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:25.0) Gecko/20100101 Firefox/25.0"); //Use Http to get the head request HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection(); //head request to minimal response urlConnection.setRequestMethod("HEAD"); length = (urlConnection).getContentLengthLong();