1

Actually I am splitting a 600x700 .jpg file using JAVA . Here the method's parameter width and height exactly same as images width and height. But during execution I got an exception related to heap memory.

 /*
 * this method will split the secureImage file
 */
private BufferedImage[] getsecureFragments(int width, int height,
        File secureFile)throws IOException {

    FileInputStream secureFileStream = new FileInputStream(secureFile);  
    BufferedImage secureimage = ImageIO.read(secureFileStream);
    int rows    = width;
    int columns = height;
    int chunks = rows *columns;
    int chunkWidth = width/width;
    int chunkHeight=height/height;

    int count = 0;  
    BufferedImage fragmentImgs[] = new BufferedImage[chunks];
    System.out.println(fragmentImgs.length);
    for (int x = 0; x < rows; x++) {  
        for (int y = 0; y < columns; y++) {  
            //Initialize the image array with image chunks  
            fragmentImgs[count] = new BufferedImage(chunkWidth, chunkHeight, secureimage.getType());  

            // draws the image chunk  
            Graphics2D grSecure = fragmentImgs[count++].createGraphics();  
            grSecure.drawImage(secureimage, 0, 0, chunkWidth, chunkHeight, chunkWidth * y, chunkHeight * x, chunkWidth * y + chunkWidth, chunkHeight * x + chunkHeight, null);  
            grSecure.dispose();  
        }  
    } 

    System.out.println("Splitting done");  

    //writing mini images into image files for test purpose  
    for (int i = 0; i < fragmentImgs.length; i++) {  
        ImageIO.write(fragmentImgs[i], "jpg", new File("F://uploads//fragmentImgs" + i + ".jpg"));  
    }  
    System.out.println("Mini images created");
    return fragmentImgs;
}//end of method getsecureFragments

Exception in thread "http-bio-8080-exec-9" java.lang.OutOfMemoryError: Java heap space

This is because of my logical lack? or Do i have to learn more about JAVA heap memory.

Vishnu KR
  • 718
  • 1
  • 8
  • 22
  • Can you post the stack trace of the error? – HelloWorld123456789 Nov 12 '15 at 11:49
  • yeah i got the mistake . Thank you – Vishnu KR Nov 13 '15 at 04:47
  • You have 420 *thousand* images held open in memory at the same time... I'm not surprised it runs out of memory. Also, take a look at [`BufferedImage.getSubimage`](https://docs.oracle.com/javase/8/docs/api/java/awt/image/BufferedImage.html#getSubimage-int-int-int-int-) -- maybe useful. – Boann Nov 17 '15 at 20:47

1 Answers1

0

You can run the JVM with more heap space e.g. add a -Xmx argument when you start the JVM.

You could also rewrite the code to copy a section, write it to disk, discard it, and then do the next section. At the moment, the logic in the program produces all of the sections, and then saves them.

BillRobertson42
  • 12,602
  • 4
  • 40
  • 57