先说下我的需求:是根据客户的名称生成一个带名字的头像,这样在一定的环境中,可以只看头像就知道谁是谁了,所以才做了一下开发;
根据需求而去做开发,从中会出现问题,而解决问题的方法做一下总结:
大致分为2步;
1.用java方法根据名字生成头像,向钉钉一样的头像,代码如下:
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.Random;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Slf4j
@Component
public class HeadPicByNickName {
/**
* 绘制字体头像
* 如果是英文名,只显示首字母大写
* 如果是中文名,只显示最后两个字
*
* @param name
* @param outputPath 文件路径
* @param fillet 圆角大小
*/
public static File generateImg(String name, String outputPath, Integer fillet) throws IOException {
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();
}
}
String outputName = PinYinUtils.toPinyin(name) + System.currentTimeMillis();
String filename = outputPath + File.separator + outputName + ".jpg";
File file = new File(filename);
//Font font = new Font("微软雅黑", Font.PLAIN, 30);
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.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)) {
// 首中次英 如 张S
g2.drawString(nameWritten, 27, 60);
} 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, fillet);
ImageIO.write(rounded, "png", file);
return file;
}
/**
* 判断字符串是否为中文
*
* @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[]{"2,168,250"};
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;
}
}
第二步,是把文件上传到云端,代码如下:
public String putObject(File file) {
// 初始化用户身份信息(secretId, secretKey)
String secretId = env.getProperty("tecent.SecretId");
String secretKey = env.getProperty("tecent.SecretKey");
COSCredentials cred = new BasicCOSCredentials(secretId, secretKey);
// 设置bucket的区域, COS地域的简称请参照 https://www.qcloud.com/document/product/436/6224
String regionName = "ap-guangzhou";
ClientConfig clientConfig = new ClientConfig(new Region(regionName));
// 生成cos客户端
COSClient cosClient = new COSClient(cred, clientConfig);
String bucketName = "main-1308557658";
String key = "web1/headPic/"+file.getName();
PutObjectRequest putObjectRequest = new PutObjectRequest(bucketName, key,file);
cosClient.putObject(putObjectRequest);
return "https://"+bucketName+".cos."+regionName+".myqcloud.com/"+key;
}
第一个方法里面是输出的是一个文件,然后放入到第二个方法里面,就能得到一个可以访问的地址,那么这个地址就是头像的地址;
再本地测试没有问题,上传到liunx就出现了问题;
为什么本地名字能显现出来,liunx上不行呢?后来就研究一下代码,发现了这里面设置了字体库,而liunx上面可能就没有这个字体,于是就想到在liunx上安装字体库,于是又进行了一下操作:
1.找到windows上对应的字体库,下载到本地桌面
然后运行命令:
给拉进去的字体文件权限赋值,然后安装字体库所需要的依赖,操作如下:
yum -y install mkfontscale mkfontdir fontconfig
然后运行命令:
mkfontscale && mkfontdir && fc-cache
fc-list | grep msyhbd.ttc
此时,在运行上面的程序,发现就正常了,问题解决了