基本原理
实现原理比较简单,计算图像中像素的灰度值,使用一些ascii字符,如"@#&$%*o!;.",粗略代表几个梯度的灰度值,根据灰度值计算需要填充的ASCII字符,假设计算得到的灰度值为gray,ASCII字符数组为someAscii,填充的ASCII字符Character=someAscii[someAscii.length * gray / 255]。
代码
如果填充每一个像素位ASCII字符,最后得到的ASCII字符文本太大,所以做了一定的压缩处理(每次计算ASCII字符后跳过一定的像素数)
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class AsciiImageCreator {
public static void create(File srcImgFile, File destAsciiImgFile) {
final String base = "@#&$%*o!;.";
String result = "";
try {
BufferedImage bufferedImage = ImageIO.read(srcImgFile);
for (int i = 0; i < bufferedImage.getHeight(); i += 32) {
for (int j = 0; j < bufferedImage.getWidth(); j += 8) {
int pixel = bufferedImage.getRGB(j, i); // 下面三行代码将一个数字转换为RGB数字
int red = (pixel & 0xff0000) >> 16;
int green = (pixel & 0xff00) >> 8;
int blue = (pixel & 0xff);
float gray = 0.299f * red + 0.578f * green + 0.114f * blue;
int index = Math.round(gray * (base.length() + 1) / 255);
result += index >= base.length() ? " " : String.valueOf(base.charAt(index));
}
result += "\r\n";
}
FileWriter fileWriter = new FileWriter(destAsciiImgFile);
fileWriter.write(result);
fileWriter.flush();
fileWriter.close();
// System.out.print(result);
} catch (IOException e) {
e.printStackTrace();
}
}
public static void create(String srcImgFile, String destAsciiImgFile) {
create(new File(srcImgFile),new File(destAsciiImgFile));
}
}