1

I am using Java (Eclipse) to build a application that works with photos.

So I used this link Java get available memory to know how much free memory I still have. The issue is that I have this code:

Main.printMemory("before image");
url = new File(information.getPath()).toURI().toURL();
image = ImageIO.read(url);
Main.printMemory("after image");

And the result is:

Message: before image
Free memory (bytes): 82554768
Maximum memory (bytes): 129957888
Total memory (bytes): 85000192

and

Message: after image
Free memory (bytes): 42600680
Maximum memory (bytes): 129957888
Total memory (bytes): 85000192

So loading that image takes 82554768 - 42600680 = 39954088 bytes = 38 MB

The photo size is 3.3 MB

Is it normal to take so much memory??? Why does it consume so much memory? Is there any way I could reduce this, hopefully maintaining the photo quality?

Community
  • 1
  • 1
Antonio
  • 139
  • 1
  • 9

2 Answers2

3

The file size of a compressed and encoded image is a bad indicator for the memory requirements to store an image. Images in main memory are usually uncompressed, because using a compressed encoding would make image operations both more complex and a lot slower.

You have a 4,000 x 3,000 JPEG image. Since the source is JPEG encoded, it might get loaded by ImageIO with TYPE_INT_RGB meaning every pixel requires 4 bytes (an int) of storage space. This means the decoded image will use up to need 4,000 x 3,000 x 4 = 48,000,000 bytes of memory. This number might even be larger when Java gets support for 16bit color depth.

That it only needs ~ 38MB sounds like the image is not fully unpacked (TYPE_INT_RGB) but actually represented in some packed encoding (e.g. TYPE_3BYTE_BGR would need 36 MB) in main memory.

Images are BIG.

dhke
  • 13,716
  • 2
  • 34
  • 54
0

It's normal, yes. The reason is that most image formats are compressed in some way -- this is true of gif, jpeg and png, for instance -- but BufferedReader is not. That is, it records data for every pixel independently, without trying to compress or consolidate this information. That yields a much bigger memory footprint: width x height x (bytes per pixel). If that last one is 4 bytes, you can see how pictures can get pretty big pretty fast.

There's not much you can do about it if you want to work with the images -- to rotate them, filter then, etc. This is why photo editing tools have always been memory hogs! If you don't need the full resolution, you can downsample the images, using something like imgscalr or some other library.

yshavit
  • 39,951
  • 7
  • 75
  • 114