Java实现的图片转字符图,求优化?
 import java.io.*;
import java.util.logging.*;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import sun.misc.BASE64Encoder;

public class ZiFuTu {

    public static void main(String[] args) throws Exception {
        //这里放张图片
        String imgPath = "D:\\NetBeansProjects\\MyJava\\src\\image\\A.png";
        FileInputStream fileInputStream = new FileInputStream(imgPath);
        BufferedImage image = ImageIO.read(fileInputStream);
        StringBuilder imageToAscii = imageToAscii(image);
        StringBuilder sb = new StringBuilder();
        System.out.println(imageToAscii);
    }

    //三十二位颜色
    private final static char[] asc = {' ', '`', '.', '^', ',', ':', '~', '"',
        '<', '!', 'c', 't', '+', '{', 'i', '7', '?', 'u', '3', '0', 'p', 'w',
        '4', 'A', '8', 'D', 'X', '%', '#', 'H', 'W', 'M'};

    public static StringBuilder imageToAscii(BufferedImage image) {
        //System.out.println(asc.length);
        StringBuilder sb = new StringBuilder();
        int width = image.getWidth();
        int height = image.getHeight();
        for (int i = 0; i < height; i++) {
            for (int j = 0; j < width; j++) {
                int rgb = image.getRGB(j, i);
                int R = (rgb & 0xff0000) >> 16;
                int G = (rgb & 0x00ff00) >> 8;
                int B = rgb & 0x0000ff;
                int gray = (R * 30 + G * 59 + B * 11 + 50) / 100;
                int index = 31 * gray / 255;
                sb.append(asc[index] + " ");
            }
            sb.append("\n");
        }
        return sb;
    }
}

往里放个图片输出的字符图会很大,如何实现字符图的压缩啊?

1个回答

如果你对图片精度要求不高,可以采样,比如如下代码可以缩小到1/4

 for (int i = 0; i < height; i += 2) {
            for (int j = 0; j < width; j += 2) {
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问