使用java分割图像

时间:2015-11-12 10:04:31

标签: java

实际上我正在使用JAVA拆分600x700 .jpg文件。这里方法的参数宽度和高度与图像宽度和高度完全相同。但在执行期间,我得到了与堆内存相关的异常。

 /*
 * 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堆内存的更多信息。

1 个答案:

答案 0 :(得分:0)

您可以运行具有更多堆空间的JVM,例如启动JVM时添加-Xmx参数。

您还可以重写代码以复制部分,将其写入磁盘,丢弃它,然后执行下一部分。目前,程序中的逻辑会生成所有部分,然后保存它们。