Files
webgame-backend/src/main/java/com/webgame/webgamebackend/common/constants/UserConstants.java
2026-06-22 10:09:40 +08:00

68 lines
2.3 KiB
Java
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
package com.webgame.webgamebackend.common.constants;
import java.nio.charset.StandardCharsets;
import java.util.Base64;
/**
* 用户相关常量
*/
public final class UserConstants {
private UserConstants() {
// 工具类禁止实例化
}
/**
* 头像背景色板14 种 Material Design 颜色)
*/
private static final String[] AVATAR_COLORS = {
"#E53935", "#D81B60", "#8E24AA", "#5E35B1",
"#3949AB", "#1E88E5", "#039BE5", "#00ACC1",
"#00897B", "#43A047", "#7CB342", "#C0CA33",
"#FB8C00", "#F4511E"
};
/**
* 默认昵称(当用户昵称为空时使用)
*/
private static final String DEFAULT_NICKNAME = "玩家";
/**
* 根据昵称生成默认头像 data URI本地 SVG无需外部 API
*
* @param nickName 用户昵称
* @return data:image/svg+xml;base64,... 格式的头像
*/
public static String generateDefaultAvatar(String nickName) {
String name = (nickName == null || nickName.isBlank()) ? DEFAULT_NICKNAME : nickName.trim();
// 取首字符作为头像文字
String initial = name.substring(0, 1);
// 根据昵称 hash 选颜色,同一昵称颜色不变
int colorIndex = Math.abs(name.hashCode()) % AVATAR_COLORS.length;
String bgColor = AVATAR_COLORS[colorIndex];
String svg = """
<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 100 100">
<circle cx="50" cy="50" r="50" fill="%s"/>
<text x="50" y="62" text-anchor="middle" font-size="40"
fill="#FFFFFF" font-family="Arial, sans-serif">%s</text>
</svg>
""".formatted(bgColor, escapeXml(initial));
String base64 = Base64.getEncoder().encodeToString(svg.getBytes(StandardCharsets.UTF_8));
return "data:image/svg+xml;base64," + base64;
}
/**
* XML 特殊字符转义(防止文字中特殊字符破坏 SVG 结构)
*/
private static String escapeXml(String text) {
return text
.replace("&", "&amp;")
.replace("<", "&lt;")
.replace(">", "&gt;")
.replace("\"", "&quot;")
.replace("'", "&apos;");
}
}