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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM