I am trying to write an application which takes an image, get red/green/blue values of each pixels, get the average value (converting into grayscale), change colors to ASCII values. The problem is that I am getting an error:
java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!
I know what does it mean, but I cant locate it in my code. Bellow my code:
public void convert(File path) {
StringBuilder sb = new StringBuilder();
int[][] red = null;
int[][] green = null;
int[][] blue = null;
int[][] avg = null;
try {
BufferedImage img = ImageIO.read(path);
red = new int[img.getHeight()][img.getWidth()];
green = new int[img.getHeight()][img.getWidth()];
blue = new int[img.getHeight()][img.getWidth()];
avg = new int[img.getHeight()][img.getWidth()];
for (int i = 0; i < img.getHeight(); i++) {
for (int j = 0; j < img.getWidth(); j++) {
int pixel = img.getRGB(i, j);
Color c = new Color(pixel, true);
red[i][j] = c.getRed();
green[i][j] = c.getGreen();
blue[i][j] = c.getBlue();
avg[i][j] = red[i][j] / 3 + green[i][j] / 3 + blue[i][j] / 3;
// ".:-=+*#%@"
if (avg[i][j] <= 25) {
sb.append("'");
} else if (avg[i][j] <= 50) {
sb.append(".");
} else if (avg[i][j] <= 75) {
sb.append(":");
} else if (avg[i][j] <= 100) {
sb.append("-");
} else if (avg[i][j] <= 125) {
sb.append("=");
} else if (avg[i][j] <= 150) {
sb.append("+");
} else if (avg[i][j] <= 175) {
sb.append("*");
} else if (avg[i][j] <= 200) {
sb.append("#");
} else if (avg[i][j] <= 225) {
sb.append("%");
} else if (avg[i][j] <= 255) {
sb.append("@");
}
}
sb.append("\n");
}
} catch (Exception e) {
System.out.println(e);
}
System.out.println(sb.toString());
}