JAVA将图片转换为ASCii字符
效果如下图:
Lena灰度图:
LenaASCii字符图
图片转换为ASCii字符
根据图片的亮度(或者称灰度)将图片转换为ASCii字符,也就是用ASCii字符代替图片的像素点或图片的分块。
RGB图转灰度图
RGB图转换为灰度图的过程为根据RGB的值,使用某种算法将其转换为一个可以表征其灰度的0-255的值。以下是一种经典的算法:f(Gray)=R∗0.299+G∗0.587+B∗0.114
ASCii字符的灰度
ASCii字符的小图片的每个像素点是一个非黑即白的灰度图,由于其体积较小,人眼在远观时可以认为这是一个很小的图片分块,而这个分块的灰度我们定义为该字符的平均灰度。
转换原理
1.将RGB图转换为Gray图
2.根据Gray图的灰度选择平均灰度相近的字符代替Gray图
java代码
public static void create(File srcImgFile, File destAsciiImgFile) {
final String base = "MNHQ&OC?7>!;:-.";
String result = "";
try {
BufferedImage bufferedImage = ImageIO.read(srcImgFile);
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 += 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();
}
}
/**
*
* @param srcImgFile 图片路径(包括图片名)
* @param destAsciiImgFile 生成的文本路径(包括文件名)
*/
public static void create(String srcImgFile, String destAsciiImgFile) {
create(new File(srcImgFile),new File(destAsciiImgFile));
}