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/4
for (int i = 0; i < height; i += 2) {
for (int j = 0; j < width; j += 2) {