java 图片转字符

 效果

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;
		}
		
	}

}

 

转载于:https://my.oschina.net/microxdd/blog/832093

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值