static BWImage removeGrayBorder(BWImage image) { float threshold = 0.9f; int w = image.getWidth(), h = image.getHeight(); int x1 = w, x2 = 0, y1 = h, y2 = 0; // haha, slow algorithm :) for (int y = 0; y < h; y++) for (int x = 0; x < w; x++) { float f = image.getPixel(x, y); if (f < threshold || f == 1) { x1 = Math.min(x1, x); x2 = Math.max(x2, x); y1 = Math.min(y1, y); y2 = Math.max(y2, y); } } if (x1 == 0 && y1 == 0 && x2 == w-1 && y2 == h-1) return image; else if (x2 < x1 || y2 < y1) null; else return image.clip(x1, y1, x2 - x1 + 1, y2 - y1 + 1); }