【图片、字符画互转】字符画实现(JAVA)

一、实现方法

字符画实际上是将图片的每一个像素点,按一定的标准(如灰度值等)替换为字符(如图所示,图示为黑色背景,白色字体)。
示例

二、图片转字符画 实现过程

①读取图片(这里使用java.jwt自带的BufferedImage对象读取)

	 /** 获取最原生的BufferedImage对象 */
     public static BufferedImage getBufferedImage(final String src) throws FileNotFoundException, IOException {
     		return ImageIO.read(new FileInputStream(new File(src.trim())));
     }

②对图片进行处理(如压缩、灰度化、二值化等),一般来说,先二值/灰度化后再压缩,效果比较好,当然具体情况具体分析
灰度化示例
下面贴上代码

	/**
 * 按设置的宽度高度比例压缩图片文件,如果width和height都大于0,则以此为基准进行压缩(可能造成图片变型)
 * 
 * @param oldFile
 *            要进行压缩的文件全路径
 * @param newFile
 *            新文件
 * @param width
 *            宽度
 * @param height
 *            高度
 * @return 返回压缩后的文件的全路径
 */
public static BufferedImage zipImageFileWithRate(BufferedImage image, int width, int height) {
	if (image == null) {
		return null;
	}
	if(width<=0&&height<=0){
		return image;
	}
	/* 对服务器上的临时文件进行处理 */
	/* 按比例压缩 */
	int w = image.getWidth(null);
	int h = image.getHeight(null);
	double bili;
	if (width > 0&&height<=0) {
		bili = width / (double) w;
		height = (int) (h * bili);
	} else if (height > 0&&width<=0) {
			bili = height / (double) h;
			width = (int) (w * bili);
	}
	
	BufferedImage buffImg = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
	Graphics2D graphics = buffImg.createGraphics();
	graphics.getFontRenderContext();
	graphics.setBackground(new Color(255, 255, 255));
	graphics.setColor(new Color(255, 255, 255));
	graphics.fillRect(0, 0, width, heigh
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值