该篇主要为解决大图片递归时栈内存溢出问题。
util改进代码:
//最大递归深度
private static int MAX_RECURSION_DEPTH = 1000;
/**
* 递归读图
* @param image
* @param i
* @param j
* @param colors 存储所有元素的总集合
*/
public static void recursion(BufferedImage image, int i, int j, Set<ColorPo> colorsAllSet) {
boolean flag = getBlackArrays(image,i,j,colorsAllSet,0);
//如果为true 说明是强制返回 需要从返回点位重新筛选。
if (flag) {
//重定义一个替身Set,用来存储该次递归中所有的参数
Set<ColorPo> substituteColorSet = new HashSet<ColorPo>(colorsAllSet);
for (ColorPo colorPo : colorsAllSet) {
recursion(image, colorPo.getX(), colorPo.getY(), substituteColorSet);
}
colorsAllSet.addAll(substituteColorSet);
//清空替身内容,并回收垃圾
substituteColorSet = null;
}
}
/**
* 获取相邻像素集合
* @param image
* @param x
* @param y
* @param colorPoSet
* @param colorPoSet
*/
public static boolean getBlackArrays(BufferedImage image,int x,int y, Set<ColorPo> colorPoSet,int RECURSION_DEPTH) {
//判断递归深度,超过深度则强制返回
if (RECURSION_DEPTH > MAX_RECURSION_DEPTH) {
return true;
}
ColorPo colorPo = null;
for (int sy = 1; sy >= -1; sy--) {
for (int sx = 1; sx >= -1; sx--) {
if (sx == 0 ? sx == sy : false) {
continue;
}
int startX = sx + x,startY = sy+y;
if (startX >=0 && startX < image.getWidth() && startY>= 0 && startY < image.getHeight()) {
colorPo = new ColorPo(image.getRGB(startX, startY), startX, startY);
if (colorPo.isBlack() && !colorPoSet.contains(colorPo)) {
colorPoSet.add(colorPo);
boolean flag = getBlackArrays(image, startX, startY,colorPoSet,++RECURSION_DEPTH);
//返回递归状态码
if (flag) {
return flag;
}
}
}
}
}
return false;
}