将一张图片转换为ASCII字符图像
原图:
效果图:
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
public class ImageToASCII {
/**
* 将图片转换为ASCII艺术字符图像
*
* @param imgPath 图片路径(包括图片名)
* @param outPath 生成的文本路径(包括文件名)
*/
public static void imageToASCII(String imgPath, String outPath) {
// 表示不同灰度级别的ASCII字符
final String base = "MNHQ&OC?7>!;:-.";
StringBuffer result = new StringBuffer("");
try {
long start = System.currentTimeMillis();
System.out.println("开始执行:");
BufferedImage bufferedImage = ImageIO.read(new File(imgPath));
// 使用嵌套的循环遍历图像的像素,每次处理一个区块(36 x 9像素)当前为 i=3 x j=2。
for (int i = 0; i < bufferedImage.getHeight(); i += 3) {
for (int j = 0; j < bufferedImage.getWidth(); j += 2) {
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.append(index >= base.length() ? " " : String.valueOf(base.charAt(index)));
}
result.append("\r\n");
}
FileWriter fileWriter = new FileWriter(outPath);
fileWriter.write(result.toString());
fileWriter.flush();
fileWriter.close();
long end = System.currentTimeMillis();
System.out.println("执行结束:共执行 " + (end - start) + "毫秒");
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) {
imageToASCII("E:\\images\\水娃.jpg", "E:\\images\\222.txt");
}
}