Search code examples
javaimagejavafxjasper-reportsheap-memory

How to fix java heap space out of memory when using many successive images


Trying to perform some printings using JasperReport.

JasperReport provides a function to print a document to a BufferedImage, which i convert to a WritableImage to display it on an ImageView object (as shown in the code below).

By time i get a Java Heap space out of memory exception in the getImage(int pageNumber) function. My guess is that the old references to the images are not freed.

Is it possible to fix that ?

private void viewPage(int pageNumber) throws JRException {
    this.resultViewer.setFitHeight(this.imageHeight * this.zoomFactor);
    this.resultViewer.setFitWidth(this.imageWidth * this.zoomFactor);
    this.resultViewer.setImage(this.getImage(pageNumber));
}

@FXML
private ImageView resultViewer;

private WritableImage getImage(int pageNumber) throws JRException {
    return SwingFXUtils
            .toFXImage((BufferedImage) JasperPrintManager.printPageToImage(this.jasperPrint, pageNumber, 2), null);
}

Solution

  • I fixed the problem by caling flush() function on the last displayed BufferedImage before displaying a next one