Search code examples
javaarraylistout-of-memorybufferedimage

Store thousands of BufferedImages in ArrayList without using up all memory - Java


I am trying to make a screen recording app. I have code that takes a screenshot using java.awt.Robot.createScreenCapture and then stores the output in an arraylist. The arraylist needs to store 7500 images. I need to be able to access any of the BufferedImages very quickly. I have tried converting the BufferedImages into byte[] and then storing them, but converting them back to bufferedimages takes too long (about 1 second). Is there a way I could do this without having to add command line arguments?

Error: Exception in thread "AWT-EventQueue-0" java.lang.OutOfMemoryError: Java heap space

Code:

static ArrayList < BufferedImage > bilist = new ArrayList < BufferedImage > ();
public static Timer recordingTimer = new Timer (40, new ActionListener () {

    public void actionPerformed ( ActionEvent e ) {

        try {

            BufferedImage bimage = robot.createScreenCapture(wholescreen);
            bilist.add(bimage);
            if ( bilist.size() > 7500 ) bilist.remove(7500);

        } catch ( Exception ex ) {

            ex.printStackTrace();

        }

    }

});

Solution

  • Real solution: compress frames with a hardware-accelerated video encoder (or software encoder if you can afford CPU)

    Old answer:

    I have solved my problem! What I did was I changed 5 minutes of recording to 15 seconds, then I changed the type of the BufferedImages to TYPE_BYTE_INDEXED, then I halved the images dimensions, and then I lowered the frame rate. In the future, I might make this same program working with Gilbert Le Blanc's system (look at comment above).