简体   繁体   中英

Get Image Dimension and Image Size from Binary

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.

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?

Many thanks

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();
}

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:

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

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

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM