浏览代码

增加用户头像按照姓名默认生成

hurugang 6 年之前
父节点
当前提交
a3f920be8a

+ 170 - 8
src/main/java/cn/hnthyy/thmz/Utils/ImageUtil.java

@@ -10,6 +10,9 @@ import java.awt.geom.Area;
 import java.awt.geom.RoundRectangle2D;
 import java.awt.image.BufferedImage;
 import java.io.*;
+import java.util.Random;
+import java.util.regex.Matcher;
+import java.util.regex.Pattern;
 import javax.imageio.ImageIO;
 
 /**
@@ -228,7 +231,7 @@ public class ImageUtil {
      * @param size
      * @throws IOException
      */
-    public static byte[] formatToSquare(byte[] bytes, String formatName, Integer size) throws IOException {
+    public static byte[] formatToSquare(byte[] bytes, String formatName, Integer size) {
         ByteArrayOutputStream out = null;
         if (size == null) {
             size = 250;
@@ -240,7 +243,6 @@ public class ImageUtil {
             if (image.getTransparency() == Transparency.TRANSLUCENT) {
                 image = get24BitImage(image);
             }
-
             out = new ByteArrayOutputStream();
             ImageIO.write(image, formatName, out);
             return out.toByteArray();
@@ -248,17 +250,177 @@ public class ImageUtil {
             log.error("图片转码失败,错误原因:{}", e.getMessage());
         } finally {
             if (out != null) {
-                out.close();
+                try {
+                    out.close();
+                } catch (IOException e) {
+                    log.error("图片转码流关闭失败,错误原因:{}", e.getMessage());
+                }
             }
         }
         return null;
     }
 
 
-    public static void main(String[] args) throws IOException {
-//        File img = new File("C:\\Users\\Administrator\\Desktop\\back.jpg");
-//        File save = new File("C:\\Users\\Administrator\\Desktop\\111111112.jpg");
-//        toJPG(img, save, 250);
-        System.out.println("back.jpg".substring("back.jpg".indexOf(".") + 1));
+
+
+
+    /**
+     * 绘制字体头像
+     * 如果是英文名,只显示首字母大写
+     * 如果是中文名,只显示最后两个字
+     *
+     * @param name
+     * @throws IOException
+     */
+    public static  byte[] generateImg(String name){
+        ByteArrayOutputStream out = null;
+        int width = 100;
+        int height = 100;
+        int nameLen = name.length();
+        String nameWritten;
+        //如果用户输入的姓名少于等于2个字符,不用截取
+        if (nameLen <= 2) {
+            nameWritten = name;
+        } else {
+            //如果用户输入的姓名大于等于3个字符,截取后面一位  可根据需求改长度
+            String first = name.substring(0, 1);
+            if (isChinese(first)) {
+                //截取倒数两位汉字
+                nameWritten = name.substring(nameLen - 2);
+            } else {
+                //截取前面的两个英文字母
+                nameWritten = name.substring(0, 2).toUpperCase();
+            }
+        }
+        BufferedImage bi = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
+        Graphics2D g2 = (Graphics2D) bi.getGraphics();
+        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING,
+                RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
+        //g2.setBackground(getRandomColor());
+        //钉钉色
+        g2.setBackground(new Color(50, 150, 250));
+        g2.clearRect(0, 0, width, height);
+        g2.setPaint(Color.WHITE);
+        Font font = null;
+        //两个字及以上
+        if (nameWritten.length() >= 2) {
+            font = new Font("微软雅黑", Font.PLAIN, 30);
+            g2.setFont(font);
+            String firstWritten = nameWritten.substring(0, 1);
+            String secondWritten = nameWritten.substring(1, 2);
+            //两个中文
+            if (isChinese(firstWritten) && isChinese(secondWritten)) {
+                g2.drawString(nameWritten, 20, 60);
+            }
+            //首中次英
+            else if (isChinese(firstWritten) && !isChinese(secondWritten)) {
+                g2.drawString(nameWritten, 27, 60);
+                //首英,如 AB
+            } else {
+                nameWritten = nameWritten.substring(0, 1);
+            }
+        }
+        //一个字
+        if (nameWritten.length() == 1) {
+            //中文
+            if (isChinese(nameWritten)) {
+                font = new Font("微软雅黑", Font.PLAIN, 50);
+                g2.setFont(font);
+                g2.drawString(nameWritten, 25, 70);
+            }
+            //英文
+            else {
+                font = new Font("微软雅黑", Font.PLAIN, 55);
+                g2.setFont(font);
+                g2.drawString(nameWritten.toUpperCase(), 33, 67);
+            }
+        }
+        BufferedImage rounded = makeRoundedCorner(bi, 99);
+        try {
+            out = new ByteArrayOutputStream();
+            ImageIO.write(rounded, "png", out);
+            return out.toByteArray();
+        }catch (Exception e){
+            log.error("根据用户姓名生成头像出错,异常信息:{}",e.getMessage());
+        }finally {
+            if(out!=null){
+                try {
+                    out.close();
+                } catch (IOException e) {
+                    log.error("根据用户姓名生成头像流关闭失败,异常信息:{}",e.getMessage());
+                }
+            }
+        }
+        return null;
+    }
+
+
+    /**
+     * 判断字符串是否为中文
+     *
+     * @param str
+     * @return
+     */
+    public static boolean isChinese(String str) {
+        String regEx = "[\\u4e00-\\u9fa5]+";
+        Pattern p = Pattern.compile(regEx);
+        Matcher m = p.matcher(str);
+        if (m.find())
+            return true;
+        else
+            return false;
+    }
+
+    /**
+     * 获得随机颜色
+     *
+     * @return
+     */
+    private static Color getRandomColor() {
+        String[] beautifulColors =
+                new String[]{"232,221,203", "205,179,128", "3,101,100", "3,54,73", "3,22,52",
+                        "237,222,139", "251,178,23", "96,143,159", "1,77,103", "254,67,101", "252,157,154",
+                        "249,205,173", "200,200,169", "131,175,155", "229,187,129", "161,23,21", "34,8,7",
+                        "118,77,57", "17,63,61", "60,79,57", "95,92,51", "179,214,110", "248,147,29",
+                        "227,160,93", "178,190,126", "114,111,238", "56,13,49", "89,61,67", "250,218,141",
+                        "3,38,58", "179,168,150", "222,125,44", "20,68,106", "130,57,53", "137,190,178",
+                        "201,186,131", "222,211,140", "222,156,83", "23,44,60", "39,72,98", "153,80,84",
+                        "217,104,49", "230,179,61", "174,221,129", "107,194,53", "6,128,67", "38,157,128",
+                        "178,200,187", "69,137,148", "117,121,71", "114,83,52", "87,105,60", "82,75,46",
+                        "171,92,37", "100,107,48", "98,65,24", "54,37,17", "137,157,192", "250,227,113",
+                        "29,131,8", "220,87,18", "29,191,151", "35,235,185", "213,26,33", "160,191,124",
+                        "101,147,74", "64,116,52", "255,150,128", "255,94,72", "38,188,213", "167,220,224",
+                        "1,165,175", "179,214,110", "248,147,29", "230,155,3", "209,73,78", "62,188,202",
+                        "224,160,158", "161,47,47", "0,90,171", "107,194,53", "174,221,129", "6,128,67",
+                        "38,157,128", "201,138,131", "220,162,151", "137,157,192", "175,215,237", "92,167,186",
+                        "255,66,93", "147,224,255", "247,68,97", "185,227,217"};
+        int len = beautifulColors.length;
+        Random random = new Random();
+        String[] color = beautifulColors[random.nextInt(len)].split(",");
+        return new Color(Integer.parseInt(color[0]), Integer.parseInt(color[1]),
+                Integer.parseInt(color[2]));
+    }
+
+
+    /**
+     * 图片做圆角处理
+     *
+     * @param image
+     * @param cornerRadius
+     * @return
+     */
+    public static BufferedImage makeRoundedCorner(BufferedImage image, int cornerRadius) {
+        int w = image.getWidth();
+        int h = image.getHeight();
+        BufferedImage output = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
+        Graphics2D g2 = output.createGraphics();
+        g2.setComposite(AlphaComposite.Src);
+        g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
+        g2.setColor(Color.WHITE);
+        g2.fill(new RoundRectangle2D.Float(0, 0, w, h, cornerRadius, cornerRadius));
+        g2.setComposite(AlphaComposite.SrcAtop);
+        g2.drawImage(image, 0, 0, null);
+        g2.dispose();
+        return output;
     }
 }  

+ 0 - 2
src/main/java/cn/hnthyy/thmz/controller/LoginController.java

@@ -95,8 +95,6 @@ public class LoginController {
         }
         Date deadTime = DateUtil.getDate(Constants.JWT_TTL);
         String token =TokenUtil.createJWT(JsonUtil.object2Json(user),deadTime);
-//        Token tokenObject = new Token(token, deadTime, new Date());
-//        tokenService.saveToken(tokenObject);
         resultMap.put("code", 0);
         resultMap.put("token", token);
         resultMap.put("message", "恭喜您,登录成功!");

+ 18 - 3
src/main/java/cn/hnthyy/thmz/controller/UserController.java

@@ -112,14 +112,29 @@ public class UserController {
 
 
     /**
-     * 测试方法
+     * 获取当前登录用户的姓名
      * @return
      */
     @UserLoginToken
-    @RequestMapping(value = "/test", method = RequestMethod.POST)
-    public Map<String, Object> test() {
+    @RequestMapping(value = "/getUserName", method = RequestMethod.GET)
+    public Map<String, Object> getUserName(HttpServletRequest httpServletRequest) {
         Map<String, Object> resultMap = new HashMap<>();
+        String token = TokenUtil.getToken(httpServletRequest);
+        DecodedJWT decodedJWT=TokenUtil.parseJWT(token);
+        User tokenUser=(User)JsonUtil.jsontoObject(decodedJWT.getSubject(),User.class);
+        if(tokenUser==null || tokenUser.getId()==null){
+            resultMap.put("code", -1);
+            resultMap.put("message", "用户信息查询失败,用户主键不能为空");
+            return resultMap;
+        }
+        User userDb= userService.queryUserById(tokenUser.getId());
+        if (userDb == null) {
+            resultMap.put("code", -1);
+            resultMap.put("message", "用户信息查询失败,用户不存在");
+            return resultMap;
+        }
         resultMap.put("code", 0);
+        resultMap.put("data", userDb);
         resultMap.put("message", "用户信息查询成功!");
         return resultMap;
     }

+ 7 - 2
src/main/java/cn/hnthyy/thmz/entity/thmz/User.java

@@ -1,6 +1,7 @@
 package cn.hnthyy.thmz.entity.thmz;
 
 import lombok.Data;
+import org.apache.commons.lang3.StringUtils;
 
 import java.util.Date;
 
@@ -45,8 +46,12 @@ public class User {
     }
 
     public User(String userCode, String userName, Integer status) {
-        this.userCode = userCode;
-        this.userName = userName;
+        if(StringUtils.isNotBlank(userCode)){
+            this.userCode = userCode.trim();
+        }
+        if(StringUtils.isNotBlank(userName)){
+            this.userName = userName.trim();
+        }
         this.status = status;
     }
 }

+ 0 - 2
src/main/java/cn/hnthyy/thmz/service/impl/thmz/TokenServiceImpl.java

@@ -1,9 +1,7 @@
 package cn.hnthyy.thmz.service.impl.thmz;
 
-import cn.hnthyy.thmz.Utils.JsonUtil;
 import cn.hnthyy.thmz.Utils.TokenUtil;
 import cn.hnthyy.thmz.entity.thmz.Token;
-import cn.hnthyy.thmz.entity.thmz.User;
 import cn.hnthyy.thmz.mapper.thmz.TokenMapper;
 import cn.hnthyy.thmz.service.thmz.TokenService;
 import com.auth0.jwt.interfaces.DecodedJWT;

+ 23 - 2
src/main/java/cn/hnthyy/thmz/service/impl/thmz/UserServiceImpl.java

@@ -1,12 +1,16 @@
 package cn.hnthyy.thmz.service.impl.thmz;
 
+import cn.hnthyy.thmz.Utils.ImageUtil;
 import cn.hnthyy.thmz.common.Constants;
+import cn.hnthyy.thmz.entity.thmz.FileUpload;
 import cn.hnthyy.thmz.entity.thmz.User;
+import cn.hnthyy.thmz.mapper.thmz.FileUploadMapper;
 import cn.hnthyy.thmz.mapper.thmz.UserMapper;
 import cn.hnthyy.thmz.service.thmz.UserService;
 import org.apache.commons.lang3.StringUtils;
 import org.springframework.beans.factory.annotation.Autowired;
 import org.springframework.stereotype.Service;
+import org.springframework.transaction.annotation.Transactional;
 
 import java.util.Date;
 
@@ -15,7 +19,9 @@ public class UserServiceImpl implements UserService {
     @SuppressWarnings("all")
     @Autowired
     private UserMapper userMapper;
-
+    @SuppressWarnings("all")
+    @Autowired
+    private FileUploadMapper fileUploadMapper;
     @Override
     public User queryUserById(Long id) {
         return userMapper.selectUserById(id);
@@ -26,6 +32,7 @@ public class UserServiceImpl implements UserService {
         return userMapper.selectUserByCode(userCode);
     }
 
+    @Transactional
     @Override
     public int saveUser(User user) {
         if(user!=null){
@@ -39,7 +46,21 @@ public class UserServiceImpl implements UserService {
                 user.setCreateTime(new Date());
            }
         }
-        return userMapper.insertUser(user);
+        int num=userMapper.insertUser(user);
+        if(StringUtils.isNotBlank(user.getUserName())){
+            byte[] bytes=ImageUtil.generateImg(user.getUserName());
+            FileUpload newFile = new FileUpload(user.getUserName()+".png", bytes, "image/jpeg");
+            newFile.setSquareFile(bytes);
+            newFile.setCreateUser(user.getId());
+            fileUploadMapper.insertFileUpload(newFile);
+            User updateUser = new User();
+            updateUser.setId(user.getId());
+            updateUser.setProfileImage(newFile.getId());
+            updateUser.setUpdateUser(Constants.DEFAULT_USER_ID);
+            updateUser.setUpdateTime(user.getCreateTime());
+            userMapper.updateUser(updateUser);
+        }
+        return num;
     }
 
     @Override

+ 5 - 2
src/main/resources/static/js/menu.js

@@ -4,15 +4,18 @@ $(function (){
     }
 
     $.ajax({
-        type: "POST",
+        type: "GET",
         contentType: "application/json;charset=UTF-8",
-        url: "/thmz/test",
+        url: "/thmz/getUserName",
         headers:{'Accept': 'application/json','Authorization':'Bearer '+ localStorage.getItem("token")},
         success: function(result) {
             if(result=='401' || result==401){
                 window.location.href='/thmz/login/view'
                 return;
             }
+            if(result.code ==0){
+                $(".current_user").html(result.data.userName);
+            }
         }
     });
 

+ 3 - 3
src/main/resources/templates/menu.html

@@ -41,8 +41,8 @@
                         <img id="headImage5" src="" alt="..." class="img-circle profile_img">
                     </div>
                     <div class="profile_info">
-                        <span>Welcome,</span>
-                        <h2>John Doe</h2>
+                        <span>欢迎,</span>
+                        <h2 class="current_user"></h2>
                     </div>
                 </div>
                 <!-- /menu profile quick info -->
@@ -189,7 +189,7 @@
                         <li class="">
                             <a href="javascript:;" class="user-profile dropdown-toggle" data-toggle="dropdown"
                                aria-expanded="false">
-                                <img id="headImage" src="" alt="">John Doe
+                                <img id="headImage" src="" alt=""><span class="current_user"></span>
                                 <span class=" fa fa-angle-down"></span>
                             </a>
                             <ul class="dropdown-menu dropdown-usermenu pull-right">