0

I'd like to instanciate a BufferedImage class , So I added this snippet

BufferedImage bufferedImage = new BufferedImage(7232, 7204, BufferedImage.TYPE_INT_RGB);

but I get a weird Exception

java.lang.OutOfMemoryError: Java heap space

So I need to know :

How can I fix it?

trincot
  • 317,000
  • 35
  • 244
  • 286
Lamloumi Afif
  • 8,941
  • 26
  • 98
  • 191
  • 2
    "Thrown when the Java Virtual Machine cannot allocate an object because it is out of memory, and no more memory could be made available by the garbage collector. OutOfMemoryError objects may be constructed by the virtual machine as if suppression were disabled and/or the stack trace was not writable." -- http://docs.oracle.com/javase/7/docs/api/java/lang/OutOfMemoryError.html – Marco Acierno Jun 24 '15 at 12:09
  • Maybe it's throw because you are trying to allocate memory for an 7232x7204 image and it doesn't have memory? – Marco Acierno Jun 24 '15 at 12:11
  • @MarcoAcierno : thanks, but How can I resolve this issue? – Lamloumi Afif Jun 24 '15 at 12:11

1 Answers1

1

You need to make sure you start the JVM which runs this program with enough heap space. The command line option -Xmx sets the max amount of heap available to the jvm. For example: java -Xmx 2048m

There are different ways of settings this parameter, dependent upon how you start the program. The above way works if you're starting it directly from the commandline but if you are using an IDE such as Eclipse you might want to look into the 'run' or 'launch' configuration.

However, there is a limit upon the amount of heap space you can make available to the jvm, defined by your machine's system properties (hardware constraints).

See also How to deal with "java.lang.OutOfMemoryError: Java heap space" error (64MB heap size) for an in-depth discussion.

EDIT: BufferedImage seems to load the bitmap in memory which can make your application really memory intensive real quick. This is great if you want to manipulate the image before rendering but might be a bit overkill if you just want to display the image. I have very limited experience working with images in Java and I don't know of any class that allows for lower memory consumption when handling images but Make a BufferedImage use less RAM? proposes a solution where the image is downsized upon reading so your BufferedImages use less memory. I don't know if it works but it might point you in the right direction.

P.S. Google is your friend in most if not all questions ;-)

Community
  • 1
  • 1
Buurman
  • 1,914
  • 17
  • 26
  • Thank you @Buurman, I tried it and it works but my machine become very slow and the result is not guaranteed in the client machines. Is there another class which can be used instead of `bufferedImage` which fix this problem? – Lamloumi Afif Jun 25 '15 at 09:33
  • @LamloumiAfif I found a similar question on SO, appended my answer. – Buurman Jun 25 '15 at 09:55