效果:
代码:
package xdemo;
import java.awt.image.BufferedImage;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import javax.imageio.ImageIO;
import javax.swing.filechooser.FileSystemView;
public class Test {
//将本地桌面上的picts文件夹内的图片转化为字符画
public static void main(String[] args) throws Exception {
String path1 = FileSystemView.getFileSystemView().getHomeDirectory().getAbsolutePath();
path1 += "\\picts";
String pathSource = "";
String pathTarget = "";
File picts = new File(path1);
if (picts.exists()) {
File[] files = picts.listFiles();
for (File file : files) {
// 判断文件是否为图片,支持bmp/gif/jpg/png
if (ImageIO.read(file) != null) {
String fileName = file.getName();
pathSource = path1 + "\\" + fileName;
pathTarget = path1 + "\\" + fileName.split("\\.")[0] + ".txt";
createAsciiPic(pathSource, pathTarget);
}
}
}
}
/**
* @param path
* 图片路径
*/
public static void createAsciiPic(final String path, String path2) {
final String base = "\"@#&$%*o!;.";// 字符串由复杂到简单
// final String base = "#8XOHLTI)i=+;:,. ";// 字符串由复杂到简单
try {
final BufferedImage image = ImageIO.read(new File(path)); // 读取图片
// 输出到指定文件中
final BufferedWriter fos = new BufferedWriter(new FileWriter(path2,
false)); // true表示是否追加
for (int y = 0; y < image.getHeight(); y += 2) {
for (int x = 0; x < image.getWidth(); x++) {
final int pixel = image.getRGB(x, y);
final int r = (pixel & 0xff0000) >> 16, g = (pixel & 0xff00) >> 8, b = pixel & 0xff;
final float gray = 0.299f * r + 0.578f * g + 0.114f * b;
final int index = Math.round(gray * (base.length() + 1)
/ 255);
String s = index >= base.length() ? " " : String.valueOf(base.charAt(index));
fos.write(s);
}
fos.newLine();
}
fos.close();
} catch (final IOException e) {
e.printStackTrace();
}
}
}