java合成图片并添加文字

来源:互联网 发布:高中网络课程哪个好 编辑:程序博客网 时间:2024/06/07 02:29
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;}

阅读全文
0 0
原创粉丝点击