3

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

Kevin
  • 5,972
  • 17
  • 63
  • 87

4 Answers4

4
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();
}
Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74
  • 1
    Thanks for your answer. I don't have a file to be processed. The image comes as a binary form. – Kevin Aug 29 '13 at 10:00
  • 1
    @Kevin You have to read all the bytes. This might help: http://www.java2s.com/Tutorial/Java/0180__File/GetbytesfromInputStream.htm – Sajal Dutta Aug 29 '13 at 10:11
3

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.

davioooh
  • 23,742
  • 39
  • 159
  • 250
2

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.

Victor Petit
  • 2,632
  • 19
  • 19
1

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();
Moritz Petersen
  • 12,902
  • 3
  • 38
  • 45