图片转成ASCII字符

package com.test;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;

/**
 * @author denis.huang
 * @since 2017/8/10
 */
public class AsciiPic {
    /**
     * @param imgPath 图片路径
     * @param outPath 输出路径
     * @param acc 精度,最小1
     */
    public static void createAsciiPic(String imgPath, String outPath, int acc) {
        String base = "#@&$%87Oo!;^~.";// 字符串由复杂到简单
        try {
            FileWriter fw = new FileWriter(outPath);
            BufferedImage image = ImageIO.read(new File(imgPath));
            for (int y = 0; y < image.getHeight(); y += 2*acc) {
                for (int x = 0; x < image.getWidth(); x += acc) {
                    int pixel = image.getRGB(x, y);
                    int r = (pixel & 0xff0000) >> 16;
                    int g = (pixel & 0xff00) >> 8;
                    int b = pixel & 0xff;
                    float gray = 0.299f * r + 0.578f * g + 0.114f * b;
                    int index = Math.round(gray * (base.length() + 1) / 255);
                    fw.write(index >= base.length() ? " " : String.valueOf(base.charAt(index)));
                }
                fw.write("\r\n");
            }
            fw.close();
        } catch (final IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(final String[] args) {
        AsciiPic.createAsciiPic("C:\\133859.jpg", "D:\\123.txt", 10);
    }
}
posted @ 2018-03-19 18:17  开不了囧  阅读(527)  评论(0编辑  收藏  举报