使用Java将图像输出成字符画

来源:互联网 发布:淘宝直通车定时投放 编辑:程序博客网 时间:2024/06/14 18:29

代码不是我写的,但是又找不到来源,抱歉不能给出出处!

直接在终端编译运行代码,根据提示输入原图文件路径后即可输出ASCII字符画,如果输出的字符画太大或者模糊,根据提示调整缩放比例即可。

import javax.imageio.ImageIO;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.util.Scanner;public class Image2Ascii {    public static void main(String[] args) {        StringBuilder builder;  // 输出的字符图像        File file;  // 图像源文件        BufferedImage image;        Scanner scanner = new Scanner(System.in);        String path;        float scaleX;        float scaleY;        while (true) {            System.out.print("请输入源图像文件的位置:");            path = scanner.next();            file = new File(path);            try {                image = ImageIO.read(file);            } catch (IOException e) {                System.out.println();                System.out.println("无法读取该文件!请检查该文件是否存在。\n");                continue;            }            System.out.println();            break;        }        while (true) {            System.out.println("请分别输入要输出的字符图像的水平和垂直方向的缩放比例");            System.out.println("(注:两个缩放比例的取值区间为(0, 1],1为原始尺寸):");            System.out.print("水平缩放比例:");            scaleX = scanner.nextFloat();            System.out.print("垂直缩放比例:");            scaleY = scanner.nextFloat();            System.out.println();            if (scaleX <= 0 || scaleX > 1 || scaleY <= 0 || scaleY > 1) {                System.out.println("错误的缩放比例!\n");                continue;            }            break;        }        builder = imageToAscii(image, scaleX, scaleY);        System.out.println(builder);    }    public static StringBuilder imageToAscii(BufferedImage image, float scaleX, float scaleY) {        // 灰阶        char[] asc = {' ', '`', '.', '^', ',', ':', '~', '"', '<', '!',                'c', 't', '+', '{', 'i', '7', '?', 'u', '3', '0', 'p',                'w', '4', 'A', '8', 'D', 'X', '%', '#', 'H', 'W', 'M'};        StringBuilder sb = new StringBuilder();        int width = image.getWidth();        int height = image.getHeight();        for (int i = 0; i < height; i += (int) (1 / scaleY)) {            for (int j = 0; j < width; j += (int) (1 / scaleX)) {                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;    }}
原创粉丝点击