Please wait. This can take some minutes ...
Many resources are needed to download a project. Please understand that we have to compensate our server costs. Thank you in advance.
Project price only 1 $
You can buy this project and download/modify it how often you want.
com.nxyfan.framework.common.util.CommonAvatarUtil Maven / Gradle / Ivy
package com.nxyfan.framework.common.util;
import cn.hutool.core.convert.Convert;
import cn.hutool.core.img.ImgUtil;
import cn.hutool.core.io.resource.InputStreamResource;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.extra.spring.SpringUtil;
import cn.hutool.http.HttpUtil;
import lombok.Cleanup;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.springframework.web.multipart.MultipartFile;
import net.sourceforge.pinyin4j.PinyinHelper;
import net.sourceforge.pinyin4j.format.HanyuPinyinCaseType;
import net.sourceforge.pinyin4j.format.HanyuPinyinOutputFormat;
import net.sourceforge.pinyin4j.format.HanyuPinyinToneType;
import net.sourceforge.pinyin4j.format.exception.BadHanyuPinyinOutputFormatCombination;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.nxyfan.framework.common.cache.CommonCacheOperator;
import com.nxyfan.framework.common.constant.CommonConstant;
import com.nxyfan.framework.common.exception.CommonException;
/**
* 通用头像工具类,生成文字头像
*
* @author amour
* @date 2022/7/5 17:36
**/
public class CommonAvatarUtil {
/**
*
* Describe: 绘制字体头像,如果是英文名,只显示首字母大写,如果是中文名,只显示最后两个字
* Author: caoyang
* Create Time: 2023年3月21日 下午2:40:52
* @param name 名称
* @return 返回图片地址
*/
public static String generateImg(String name) {
int width = 100;
int height = 100;
int nameLength = name.length();
String nameWritten;
// 如果用户输入的姓名少于等于2个字符,不用截取
if(nameLength <= 2) {
nameWritten = name;
}else {
// 如果用户输入的姓名大于等于3个字符,截取后面两位
String first = StrUtil.sub(name, 0, 1);
if(isChinese(first)) {
// 截取倒数两位汉字
nameWritten = name.substring(nameLength - 2);
}else {
// 截取前面的两个英文字母
nameWritten = StrUtil.sub(name, 0, 1).toUpperCase();
}
}
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics2D g2 = (Graphics2D) bufferedImage.getGraphics();
g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
g2.setBackground(getRandomColor());
g2.clearRect(0, 0, width, height);
g2.setPaint(Color.WHITE);
Font font;
// 两个字及以上
if(nameWritten.length() >= 2) {
font = new Font("微软雅黑", Font.BOLD, 30);
g2.setFont(font);
String firstWritten = StrUtil.sub(nameWritten, 0, 1);
String secondWritten = StrUtil.sub(nameWritten, 0, 2);
// 两个中文 如 言曌
if(isChinese(firstWritten) && isChinese(secondWritten)) {
g2.drawString(nameWritten, 20, 60);
}
// 首中次英 如 罗Q
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);
}
}
try {
CommonCacheOperator commonCacheOperator = SpringUtil.getBean(CommonCacheOperator.class);
Object cacheValue = commonCacheOperator.get(CommonConstant.REDIS_CONFIG_CACHE_KEY + CommonConstant.CONFIG_KEY_SYS_FILE_UPLOAD_PATH);
if(ObjectUtil.isEmpty(cacheValue)) {
return ImgUtil.toBase64DataUri(bufferedImage, "jpg");
}
@Cleanup
InputStream inputStream = ImgUtil.toStream(bufferedImage, "jpg");
InputStreamResource isr = new InputStreamResource(inputStream, name + ".jpg");
Map param = new HashMap<>();
param.put("file", isr);
param.put("path", "sysUser/avatar");
param.put("output", "json");
String result = HttpUtil.post(Convert.toStr(cacheValue), param);
inputStream.close();
JSONObject jsonObject = JSON.parseObject(result);
return jsonObject.getString("path");
}catch(IOException e) {
e.printStackTrace();
throw CommonException.bizException("文件上传失败");
}
}
/**
*
* Describe: 汉字转为拼音
* Author: Administrator
* Create Time: 2024年5月7日 上午8:35:29
* @param chinese
* @return 拼音
*/
public static String toPinyin(String chinese){
String pinyinStr = "";
char[] newChar = chinese.toCharArray();
HanyuPinyinOutputFormat defaultFormat = new HanyuPinyinOutputFormat();
defaultFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
defaultFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
for(int i = 0; i < newChar.length; i++) {
if(newChar[i] > 128) {
try {
pinyinStr += PinyinHelper.toHanyuPinyinStringArray(newChar[i], defaultFormat)[0];
}catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}else{
pinyinStr += newChar[i];
}
}
return pinyinStr;
}
/**
*
* Describe: 上传用户头像
* Author: Administrator
* Create Time: 2024年9月2日 上午10:13:56
* @param file
* @return 头像地址
*/
public static String uploadAvatar(MultipartFile file) {
try {
if(file.getOriginalFilename().contains("&") || file.getOriginalFilename().contains("=")) {
throw CommonException.bizException("上传的文件名不可包含=、&等特殊字符");
}
CommonCacheOperator commonCacheOperator = SpringUtil.getBean(CommonCacheOperator.class);
Object cacheValue = commonCacheOperator.get(CommonConstant.REDIS_CONFIG_CACHE_KEY + CommonConstant.CONFIG_KEY_SYS_FILE_UPLOAD_PATH);
@Cleanup
InputStream inputStream = file.getInputStream();
InputStreamResource isr = new InputStreamResource(inputStream, file.getOriginalFilename());
Map param = new HashMap<>();
param.put("file", isr);
param.put("path", "sysUser/avatar");
param.put("output", "json");
String result = HttpUtil.post(Convert.toStr(cacheValue), param);
JSONObject jsonObject = JSON.parseObject(result);
return jsonObject.getString("path");
}catch(IOException e) {
e.printStackTrace();
throw CommonException.bizException("文件上传失败,文件名为:{}", file.getOriginalFilename());
}
}
/**
*
* Describe: 获得随机颜色
* Author: caoyang
* Create Time: 2023年3月21日 上午11:08:26
* @return 随机颜色
*/
private static Color getRandomColor() {
String[] beautifulColors = new String[]{"114,101,230", "255,191,0", "0,162,174", "245,106,0", "24,144,255", "96,109,128"};
String[] color = beautifulColors[RandomUtil.randomInt(beautifulColors.length)].split(StrUtil.COMMA);
return new Color(Integer.parseInt(color[0]), Integer.parseInt(color[1]), Integer.parseInt(color[2]));
}
/**
*
* Describe: 判断字符串是否为中文
* Author: caoyang
* Create Time: 2023年3月21日 上午11:08:38
* @param str
* @return 是否为中文
*/
private static boolean isChinese(String str) {
String regEx = "[\\u4e00-\\u9fa5]+";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.find();
}
}