2015-11-12 313 views
1

實際上,我正在使用JAVA分割600x700 .jpg文件。這裏該方法的參數寬度和高度與圖像寬度和高度完全相同。但是在執行期間,我得到了與堆內存有關的異常。使用java分割圖像

/* 
* 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 

異常在線程 「HTTP-BIO-8080-EXEC-9」 java.lang.OutOfMemoryError:Java堆空間

這是因爲我的邏輯缺乏?或者我是否需要了解有關JAVA堆內存的更多信息。

+0

你能發佈錯誤的堆棧跟蹤嗎? –

+0

是的,我得到了錯誤。謝謝 –

+0

你在內存中同時打開了420 * 000 *圖像......我並不感到驚訝,它的內存不足。另外,請看['BufferedImage.getSubimage'](https://docs.oracle.com/javase/8/docs/api/java/awt/image/BufferedImage.html#getSubimage-int-int-int- int-) - 也許有用。 – Boann

回答

0

您可以使用更多堆空間運行JVM,例如在啓動JVM時添加一個-Xmx參數。

您也可以重寫代碼以複製某個節,將其寫入磁盤,放棄它,然後執行下一節。目前,程序中的邏輯產生所有的部分,然後保存它們。

+0

謝謝比爾。 –