简体   繁体   中英

Check how much memory bufferedImage in java uses?

I have a bufferedImage in Java. How do I see how much memory it takes up? Thanks in advance.

You can determine how many bytes the image data alone takes up using this:

DataBuffer buff = image.getRaster().getDataBuffer();
int bytes = buff.getSize() * DataBuffer.getDataTypeSize(buff.getDataType()) / 8;

The image itself takes up a bit more space for the color model and other bookkeeping info, but for large images, bytes will be the dominant term.

I'm not sure there's a straight-forward way to figure this out with 100% accuracy down to the number of bytes, without calculating it yourself (taking into account the color model, the size of the image, and other factors).

You can calculate the totalMemory() and freeMemory() on the heap before and after allocation, and get an estimate that way. If other objects are allocated (or collected) between your checks, your calculation won't be accurate.

This discussion talks about the size of primitive types in the JVM (an object being a collection of many primitive objects), which you can use to figure this out.

This article give an overview of memory usage in Java.

Using Runtime#totalMemory and Runtime#gc should be able to get you a very close approximation. Example:

Runtime.getRuntime().gc();Runtime.getRuntime().gc();Runtime.getRuntime().gc();
long totalUsed = Runtime.getRuntime().totalMemory();

BufferedImage image = ...

Runtime.getRuntime().gc();Runtime.getRuntime().gc();Runtime.getRuntime().gc();
totalUsed = Runtime.getRuntime().totalMemory() - total;

Calling gc multiple times increases the chance that the garbage collector will actually run, since gc is just a suggestion. Calling gc in this example ensures that no objects that would have been collected are adding to memory usage.

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