Java 从二进制获取图像尺寸和图像尺寸

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/18507180/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-12 08:38:53  来源:igfitidea点击:

Get Image Dimension and Image Size from Binary

javaimage

提问by Kevin

I am working on a project which requires some image processing.

我正在做一个需要一些图像处理的项目。

The web client is going to submit image of format jpg, png, gif tif. The server side needs to find out the dimension and the size of the image.

Web 客户端将提交 jpg、png、gif tif 格式的图像。服务器端需要找出图像的尺寸和大小。

I can see some of the Java classes achieve this by processing an image file. Is there any way/library I can use to avoid saving the binary into a file and still get the dimension?

我可以看到一些 Java 类通过处理图像文件来实现这一点。有什么方法/库可以用来避免将二进制文件保存到文件中并仍然获得维度?

Many thanks

非常感谢

回答by Moritz Petersen

You can create an image based on an InputStream, and then you know it's dimensions (@Marc, @GGrec I assume with "size" the "dimension" is meant) like this:

您可以创建基于 的图像InputStream,然后您知道它的尺寸(@Marc,@GGrec 我假设“尺寸”是“尺寸”的意思),如下所示:

    BufferedImage image = ImageIO.read(in);
    int width = image.getWidth();
    int height = image.getHeight();

回答by davioooh

If you need to know size (in bytes) of your image you could simply make something like:

如果您需要知道图像的大小(以字节为单位),您可以简单地制作如下内容:

byte[] imgBytes = // get you image as byte array
int imgSize = imgBytes.length;

If you also want to know width and height of you image, you can do this, for example:

如果您还想知道图像的宽度和高度,您可以这样做,例如:

BufferedImage img = ImageIO.read(new ByteArrayInputStream(imgBytes));

and than use getWidth()and getHeight()methods.

而不是使用getWidth()getHeight()方法。

回答by Sajal Dutta

File imageFile = new File("Pic.jpg");

double bytes = imageFile.length();

System.out.println("File Size: " + String.format("%.2f", bytes/1024) + "kb");

try{

    BufferedImage image = ImageIO.read(imageFile);
    System.out.println("Width: " + image.getWidth());
    System.out.println("Height: " + image.getHeight());

} catch (Exception ex){
    ex.printStackTrace();
}

回答by Victor Petit

If you will not proceed to any further operation on the image, you could give a try to the com.drewnoakes.metadata-extractorlibrary.

如果您不继续对图像进行任何进一步的操作,您可以尝试使用com.drewnoakes.metadata-extractor库。

Moreover ImageIO.read()can be knew to have some perf issues.

此外ImageIO.read()可以知道有一些性能问题。