转换文字为符号

思路:将字符串通过画笔,画到图像中,然后遍历图像的长宽,一个点一个点的取出该点的RGB颜色。 如果如果为文字的颜色。就用指定的字符串填充。否则也用指定的字符串填充。

package com.zf.test;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;

public class Transform {
	
	public static final String FILL = "*";
	public static final String EMPTY = " ";
	public static final int NARROW = 2 ;	//缩小倍数
	public static final int FONT_SIZE = 90;	//文字大小
	public static final String FONT_TYPE = "楷体";
	public static final int IMG_HEIGHT = 80 ;		
	public static final int FONT_WIDTH = 100 ;	//每个文字在图片中的宽度
	public static final int FONT_X = 0 ;	
	public static final int FONT_Y = 70 ;
	public static final int COLOR_ALLOWANCE = 100 ;	//颜色容差
	
	public static void main(String[] args) {
		
		String result = transform("说好的729呢");
		
		System.out.println(result);
	}

	public static String transform(String input){
		
		StringBuilder sb = new StringBuilder() ;

		/*根据文字长度,创建指定长度的Image,然后将文字写入到Image中*/
		BufferedImage bi = new BufferedImage( input.length() * FONT_WIDTH , IMG_HEIGHT , BufferedImage.TYPE_INT_RGB ) ;
		Graphics g = bi.getGraphics() ;
		Font font = new Font(FONT_TYPE , Font.BOLD , FONT_SIZE );
		g.setFont(font);  
		g.drawString( input , FONT_X , FONT_Y);

		int width = bi.getWidth() ;
		int height = bi.getHeight() ;

		/* 根据图像的长宽,逐个遍历图像的点 */
		for (int i = 0; i < height  ; i += NARROW) {

			for (int j = 0; j < width ; j += NARROW) {

				Color  color = new Color(bi.getRGB(j , i));

				int rc = (int)(Math.pow((Color.WHITE.getRed() - color.getRed()) , 2) + 
						Math.pow((Color.WHITE.getGreen() - color.getGreen()) , 2) + 
						Math.pow((Color.WHITE.getBlue() - color.getBlue()) , 2)) ;
  
				/* 根据容差值填充字符串 */
				String tmp = rc < COLOR_ALLOWANCE ? FILL :  EMPTY;
				
				sb.append(tmp);
			}
			sb.append("\n");
		}
		
		return sb.toString() ;
	}

}


打印结果(截图):




  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值