0

I was making an application in Java, and noticed after doing this:

g.drawImage(ImageIO.read(...)....);

that it consumed a lot more CPU and frames, so I started to wonder how much memory does this take up? and if there were any other better ways to draw an image.

Thanks!

3 Answers3

2

It's not the drawImage that's taking up a lot of CPU, it's the ImageIO.read(…)! Opening streams is expensive and thus should only be done once; when you first need to load the images. The best way to draw an image is to pre-load it into a BufferedImage (or if you manipulate the pixels a VolatileImage).

BufferedImage imageToDraw = ImageIO.read(getClass().getResource("path/To/Image.png"));

That path starts in the directory of your .java files. So, you'll want to add a folder containing your image(s). There are many different ways to load images, more of which are discussed here.

Then you can draw it just like you did before.

g.drawImage(imageToDraw, x, y, null);

This should be much faster. If you are still having problems with speed then this question might be useful.

Community
  • 1
  • 1
BitNinja
  • 1,477
  • 1
  • 19
  • 25
0

One possibility is using visualvm: http://visualvm.java.net. I've used it with some success.

Quick steps:

  • start your app locally
  • start visualvm
  • Tools > Options > Profiling > Misc (bottom) > Reset calibration data: Ok
  • in VVM, connect to your app i.e., in left-hand frame, double-click on pkg.YourMainClass (pid 2112)
  • Profiler tab, then click on Memory.

after initial baseline profiling is complete, you see a histogram of live objects.

You can take snapshots and compare them, set filters on packages, etc. See http://visualvm.java.net/docindex.html

0xb304
  • 93
  • 7
0

If you're reading the image rather than holding it as an instance of Image, you will be taking way too much memory up.

I highly, HIGHLY suggest to store the image as an instance of Image with ImageIO.read(params) rather than drawing it and reading it every single loop pass-through.

You'd most likely do it like this in your Canvas/JPanel/Swing Component class:

private Image myImage;

//Assume other code here

public void loadImages() {
     myImage = ImageIO.read(params);
     //load any other images
}

public void paint(Graphics g) {
     g.drawImage(myImage, x, y, null);
}

Just like any other application, resources (images, data, etc) are all loaded at the start-up.