在网上看到了使用java用字符将图片画出来的效果,感觉很好玩,所以就自己动手实现了一个
原理
原理很简单,其实就是利用java获取图片每个像素的rgb数据,将r+g+b/3求出灰度值0~255。
再将255分成多段,不同区间用不同的中文字符替代,数值小的用笔画较少的汉字替代,如“又”。反之灰度值大的用笔画多的汉字替代,如“墨”。
创建一个类,定义需要的变量
BufferedImage bi;
int r, g, b, grayLevel;
int height, width;
//创建二维数组保存处理后的字符
char[][] charImg;
写一个读取图片的方法
public void inputPicture(String path) throws IOException {
//读取图片
bi = ImageIO.read(new File(path));
}
写一个将图片按上述逻辑处理的方法
public char[][] toCharImg() throws IOException {
//获取宽高
height = bi.getHeight();
width = bi.getWidth();
//压缩图片
if (Math.max(height, width) > 200) {
int newH, newW;
if (width > height) {
newW = 200;
newH = 150 * height / width;
} else {
newH = 150;
newW = 200 * width / height;
}
height = newH;
width = newW;
BufferedImage newBi = new BufferedImage(newW, newH, bi.getType());
Graphics g = newBi.getGraphics();
g.drawImage(bi, 0, 0, newW, newH, null);
g.dispose();
bi = newBi;
}
charImg = new char[height][width];
//遍历写入二维数组
for (int x = 0; x < height; x++) {
for (int y = 0; y < width; y++) {
Color color = new Color(bi.getRGB(y, x));
r = color.getRed();
g = color.getGreen();
b = color.getBlue();
grayLevel = (r + g + b) / 3;
if (grayLevel < 51) {
charImg[x][y] = '口';
} else if (grayLevel > 50 && grayLevel < 102) {
charImg[x][y] = '又';
} else if (grayLevel > 101 && grayLevel < 153) {
charImg[x][y] = '圣';
} else if (grayLevel > 152 && grayLevel < 204) {
charImg[x][y] = '券';
} else if (grayLevel > 203) {
charImg[x][y] = '墨';
}
}
}
return charImg;
}
处理好后将图片输出
public void output(String path) throws IOException {
FileWriter fw = new FileWriter(path+"\\imgText.txt");
for(char[] arr:charImg){
for(char c:arr){
fw.write(c);
}
fw.write("\n");
}
}
写一个入口类
public class Entrance {
public static void main(String[] args) throws IOException {
Util util = new Util();
Scanner sc = new Scanner(System.in);
System.out.print("输入图片路径:");
String path = sc.next();
util.inputPicture(path);
util.toCharImg();
System.out.print("输出路径:");
String outPath = sc.next();
util.output(outPath);
System.out.print("成功");
}
}
程序到这基本就写完了,之后将程序打成jar包,使用exe4j打包成可运行的exe文件,再使用inno Setup将jre环境和exe打包,让程序能在没有java环境的电脑上运行,之后就可以发给朋友测试效果了。
最终效果

总结
没什么卵用的小项目,但挺有意思的,可以发给朋友玩一玩。
放一个自己打包好的程序链接: