效果
public class Test {
public static void main(String[] args) {
try {
//生成字符的宽高
int w=200;
int h=100;
//待要转换的图片
BufferedImage image= ImageIO.read(new File("F:/dev/work/tmp/1.jpg"));
toChars(image,genCharTable(),w,h);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static List<CharModel> genCharTable() {
Font f = new Font("黑体", Font.PLAIN, 12);
//开始字符
int start=32;
//结束字符
int endNum=500;
List<CharModel> list = new ArrayList<>(endNum-start);
for (int i = start; i < endNum; i++) {
if(f.canDisplay((char)i))
list.add(new CharModel((char)i));
}
//生成字符黑的程度生成对应表
int w=100;
BufferedImage image=new BufferedImage(w, w, BufferedImage.TYPE_BYTE_BINARY);
Graphics g = image.getGraphics();
ColorModel colorModel = image.getColorModel();
WritableRaster raster = image.getRaster();
int count=0;
for (CharModel fontModel : list) {
count=0;
for (int x = 0; x < w; x++) {
for (int y = 0; y < w; y++) {
image.setRGB(x, y, 0);
}
}
g.drawString(fontModel.c+"", 50, 50);
for (int x = 0; x < w; x++) {
for (int y = 0; y < w; y++) {
if(colorModel.getRed(raster.getDataElements(x, y, null))>0)
count++;
}
}
fontModel.v=count;
}
g.dispose();
//去掉黑度相近的字符后进行排序
list=list.stream().distinct().collect(Collectors.toList());
Collections.sort(list);
//toChars(list);
return list;
}
public static void toChars(BufferedImage image, List<CharModel> list2, int w, int h) {
//将图片灰度化
BufferedImage image2=new BufferedImage(w, h, BufferedImage.TYPE_BYTE_GRAY);
Graphics g = image2.getGraphics();
g.drawImage(image, 0, 0, w,h,null);
g.dispose();
ColorModel colorModel2= image2.getColorModel();
WritableRaster raster2 = image2.getRaster();
for (int x = 0; x < h; x++) {
for (int y = 0; y < w; y++) {
Object data = raster2.getDataElements( y,x, null);
int v=colorModel2.getBlue(data);
System.out.print(list2.get(v*(list2.size()-1)/255).c);
}
System.out.println();
}
}
public static class CharModel implements Comparable<CharModel>{
public int v;
public char c;
public CharModel() {
}
public CharModel(char c) {
this.c = c;
}
@Override
public int compareTo(CharModel o) {
return o.v==v?0:o.v>v?1:-1;
}
@Override
public int hashCode() {
return v;
}
@Override
public boolean equals(Object obj) {
if(obj==this)
return true;
if(obj.getClass()==this.getClass()){
CharModel fontModel=(CharModel) obj;
return fontModel.v==v;
}
return false;
}
}
}