java合成图片并添加文字

public static String generateCode(String codeUrl, Integer userId, String userName) {
	Font font = new Font("微软雅黑", Font.PLAIN, 30);// 添加字体的属性设置

	String projectUrl = PathKit.getWebRootPath() + "/before/codeImg/";
	String imgName = projectUrl + userId + ".png";
	try {
		// 加载本地图片
		String imageLocalUrl = projectUrl + "weixincode2.png";
		BufferedImage imageLocal = ImageIO.read(new File(imageLocalUrl));
		// 加载用户的二维码
		BufferedImage imageCode = ImageIO.read(new URL(codeUrl));
		// 以本地图片为模板
		Graphics2D g = imageLocal.createGraphics();
		// 在模板上添加用户二维码(地址,左边距,上边距,图片宽度,图片高度,未知)
		g.drawImage(imageCode, 575, imageLocal.getHeight() - 500, 350, 350, null);
		// 设置文本样式
		g.setFont(font);
		g.setColor(Color.BLACK);
		// 截取用户名称的最后一个字符
		String lastChar = userName.substring(userName.length() - 1);
		// 拼接新的用户名称
		String newUserName = userName.substring(0, 1) + "**" + lastChar + " 的邀请二维码";
		// 添加用户名称
		g.drawString(newUserName, 620, imageLocal.getHeight() - 530);
		// 完成模板修改
		g.dispose();
		// 获取新文件的地址
		File outputfile = new File(imgName);
		// 生成新的合成过的用户二维码并写入新图片
		ImageIO.write(imageLocal, "png", outputfile);
	} catch (Exception e) {
		e.printStackTrace();
	}
	// 返回给页面的图片地址(因为绝对路径无法访问)
	imgName = Constants.PROJECT_URL + "codeImg/" + userId + ".png";

	return imgName;
}

  • 2
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值