Java将图像转换为ascii为String

时间:2016-10-15 15:45:30

标签: java image ascii

我正在尝试编写一个应用程序来获取图像,获取每个像素的红色/绿色/蓝色值,获得平均值(转换为灰度),将颜色更改为ASCII值。问题是我收到了一个错误:

java.lang.ArrayIndexOutOfBoundsException: Coordinate out of bounds!

我知道这意味着什么,但我无法在我的代码中找到它。我的代码:

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());

    }

0 个答案:

没有答案