Kevin
Kevin

Reputation: 6302

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

Upvotes: 3

Views: 23792

Answers (4)

Victor Petit
Victor Petit

Reputation: 2692

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.

Upvotes: 2

Saj
Saj

Reputation: 18712

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

Upvotes: 4

davioooh
davioooh

Reputation: 24706

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.

Upvotes: 3

Moritz Petersen
Moritz Petersen

Reputation: 13057

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

Upvotes: 1

Related Questions