2015-11-12 314 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

谢谢比尔。 –