Win a copy of Penetration Testing Basics this week in the Security forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

java.lang.OutOfMemoryError when scaling images

Glenn Murray
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator

I'm trying to load, resize and display some jpg images. I'm not
having any problems with small images (<200 kb) but as the image sizes
grow to over 800 kb I'm running into problems.

Shrinking big files, in particular, is very slow and causing
java.lang.OutOfMemoryError (note I am running from an applet so -X
options are not available to me). First I tried

Image scaledImage
= origImage.getScaledInstance( (int) (scaler * origW),
(int) (scaler * origH),

which is very slow (many seconds) for an 800kb image. Next I tried
the ff. resize trick from one Shannon Hickey

double newW = scaler * origW;
double newH = scaler * origH;
BufferedImage scaledImage
= new BufferedImage((int)newW, (int)newH, BufferedImage.TYPE_INT_ARGB);
Graphics gr = scaledImage.getGraphics();
boolean drawOK = gr.drawImage(origImage, 0, 0, (int)newW, (int)newH, null);
scaledImage.flush(); // Not sure if this helps, but...

While this is much faster, it still suffers from OutOfMemoryError;
drawImage() returns false and I get a blank image. The other thing
I've tried is overriding paint() in a JLabel class so no intermediate
buffer is used, however this painted over my borders and I still got

Is there a better way to do this?

  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic