我正在参加「创意开发 投稿大赛」详情请看:掘金创意开发大赛来了!
记得小时候为了向隔壁桌的女同学表达爱意,经常用女生的名字画画,就算对咱没兴趣最起码也会被感动的。
最近看到一个好玩的代码块,可以把图片转为字符画,可惜这文本就是不能再缩放了,这要是弄个女朋友的头像出来,说是自己一个字一个字敲的。还不得感动的痛哭流涕的。我也试了,就是缩放不下去了,调节一下图片的大小多试几次应该可以,弄出来。各位有心的小伙伴可以试试。
先看效果图:
原图长这样
输出的txt文件打开后是这样,注意用notepad++等工具打开,txt文件直接打开会疯掉的。
全部是由一个个的小字符串组成的。
可以的可以的。
源码奉上,注意修改源文件的位置和文件名就可以了
package com.luke.demo.jpg;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
public class PrintJpg {
//三十二位颜色
private final static char[] color = {' ', '`', '.', '^', ',', ':', '~', '"',
'<', '!', 'c', 't', '+', '{', 'i', '7', '?', 'u', '3', '0', 'p', 'w',
'4', 'A', '8', 'D', 'X', '%', '#', 'H', 'W', 'M'}
/**
* 图片转字符画文本
*/
public static void createCharTxt(String path, String fileUrl) {
try {
BufferedImage image = ImageIO.read(new File(path));
StringBuilder imageToAscii = imageToAscii(image);
FileWriter fileWriter = new FileWriter(fileUrl);
fileWriter.write(imageToAscii.toString());
} catch (IOException e) {
e.printStackTrace();
}
}
/**
* 图片转字符
*/
public static StringBuilder imageToAscii(BufferedImage image) {
StringBuilder sb = new StringBuilder();
int width = image.getWidth();
int height = image.getHeight();
for (int y = 0; y < height; y++) {
for (int x= 0; x < width; x++) {
sb.append(rgbToChar(image,x,y)+ " ");
}
sb.append("\n");
}
return sb;
}
/**
* 像素转字节
*/
public static char rgbToChar(BufferedImage image,int x,int y){
int rgb = image.getRGB(x, y);
int R = (rgb & 0xff0000) >> 16;
int G = (rgb & 0x00ff00) >> 8;
int B = rgb & 0x0000ff;
int gray = (R * 30 + G * 59 + B * 11 + 50) / 100;
int index = 31 * gray / 255;
return color[index];
}
public static void main(String[] args) throws IOException {
createCharTxt("C:\Users\Administrator\Downloads\222.jpeg","C:\Users\Administrator\Downloads\222.txt");
}
}
记得一定要说是自己一个字一个字敲的哈,咱Java程序员也浪漫。哈哈