当前位置:网站首页>如何生成二维码图片(添加中文标识),并保存到指定的图片静态服务地址,解决二维码汉字不存在得问题。
如何生成二维码图片(添加中文标识),并保存到指定的图片静态服务地址,解决二维码汉字不存在得问题。
2022-06-09 19:00:00 【_王小义_】
在开发过程中会有遇到链接转成二维码的需求,明确了链接的拼接内容之后,我们就可以着手写二维码的生成了
导入生成二维码需要的依赖,
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.0</version>
</dependency>
书写实现类,为了区分二维码,我们在图片下方添加了对应的汉字作为标识。
@Service
@Slf4j
public class QrCodeGeneratorServiceImpl implements IQrCodeGenertorService {
private int WIDTH = 350;
private int HEIGHT = 350;
private String SUFFIX = "png";
private String IMG_SUFFIX = ".png";
@Value("${qr.code.path}")
private String filePath;
@Value("${qr.code.url}")
private String url;
@Override
public String getQrCodeImage(CollectQrImageParams imageParams) {
try {
String pointId = imageParams.getUuid();
String pointName = imageParams.getPointName();
String qrUrl = url+"?pointId="+ pointId;
String simpleUuid = UUIDUtil.simpleUuid();
String fileName = simpleUuid + IMG_SUFFIX;
String pathName = filePath + fileName;
generateQRCodeImage(qrUrl, pointName, pathName, WIDTH, HEIGHT);
return pathName;
} catch (WriterException e) {
log.error("Could not generate QR Code, WriterException :: " + e.getMessage());
} catch (IOException e) {
log.error("Could not generate QR Code, IOException :: " + e.getMessage());
}
return "fail";
}
private void generateQRCodeImage(String qrCodeContent, String pngName, String pathName, int width, int height) throws WriterException,
IOException {
try{
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(qrCodeContent, BarcodeFormat.QR_CODE, width, height);
//存储在存储中,地址不存在则新建
File dest = new File(pathName);
if (!dest.getParentFile().exists()) {
dest.getParentFile().mkdirs();
}
BufferedImage image = toBufferedImage(bitMatrix);
if(pngName!=null) {
pressText(pngName, image);
}
//将图片写入存储中(图片服务器)
ImageIO.write(image,SUFFIX, dest);
log.info("生成二维码成功,pathName={}", pathName);
} catch (Exception e) {
e.printStackTrace();
log.error("Can not generate QR code picture. {}"+ e.getMessage());
}
}
/** * 转换二维码的图片为buffered * @param matrix * @return */
private static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);
}
}
return image;
}
/** * 给二维码图片加上文字 */
public void pressText(String pressText, BufferedImage image) throws IOException {
pressText = new String(pressText.getBytes(), "utf-8");
Graphics g = image.createGraphics();
g.setColor(Color.BLACK);
Font font = new Font("宋体", Font.PLAIN, 20);
FontMetrics metrics = g.getFontMetrics(font);
// 文字在图片中的坐标 这里设置在中间
int startX = (WIDTH - metrics.stringWidth(pressText)) / 2;
int startY = HEIGHT - 20;
g.setFont(font);
g.drawString(pressText, startX, startY);
g.dispose();
}
}
在代码部署到linux服务器后,会有发现生成的二维码中的汉字显示方框,这时候不是代码有问题,而可能是生成所需要的字体不存在,
进入服务器验证下字体的存在,/usr/share/fonts目录下查看,如果没有fonts目录的话就创建一下,有的话就检查有没有宋体的字体。
进入C:\Windows\Fonts 查找我们需要的宋体,之后上传到服务器上/usr/share/fonts/winfont,
在此目录下执行linux命令“fc-cache -fv”,扫描字体目录并生成字体信息的缓存,然后应用程序就可以"立即"使用这些新安装的字体。
重启应用即可验证。
边栏推荐
- GCC compile demo+makefile use
- 金鱼哥RHCA回忆录:DO447管理清单--章节实验
- 明细表1字符串拼接合并插入到明细表2SQL输出过程记录
- 金鱼哥RHCA回忆录:DO447管理清单--管理清单变量
- 2022 中小企业数字化论坛召开 360 企业安全云发布全新升级
- How about JPMorgan futures? Is it safe to open futures accounts?
- 德州仪器发函:下半年供需失衡将缓解!模拟芯片涨势终结?
- 嵌入式软件设计(中期总结)
- Safe account opening procedures for futures companies?
- Notes on the first drawing board
猜你喜欢

How to reduce noise by measuring current probe

Notes on the first drawing board

Pro 后台子管理员 403 问题分析

Structure design of high pressure differential probe

How to realize wireless monitoring of factory production energy consumption data?

June team learning plan!

STM32内存知识

最高月薪16K,熬过艰难时刻,终能迎来黎明的曙光~
![[database data recovery] data recovery case of SQLSERVER database file missing for unknown reasons under Windows Server Environment](/img/aa/9942e0c661032dbb9654100dc4d709.png)
[database data recovery] data recovery case of SQLSERVER database file missing for unknown reasons under Windows Server Environment

WSL attaching USB flash disk
随机推荐
测量电流探头如何降低噪音
This article explains in detail three ways for PHP to connect to MySQL database
220609-R
Resolve swap file SWP already exists problem
WSL attaching USB flash disk
[pb03f environment setup] Bluetooth 5.2 Anxin Ke pb-03f-kit development board secondary development environment setup
C# 34. UdpClient transceiver
What software is foreign exchange transaction MT4? What is the difference between MT4 and MT5? What should I pay attention to when downloading MT4?
一季度全球PC GPU出货量下滑6.2%,疫情创造大量需求至此结束
The problem of the longest valid bracket
Qt数据库应用21-数据分组导出
Causes of differential probe burnout
Structure design of high pressure differential probe
Electron常见问题 60 - 报错:Could not start audio source
音频 3A 处理实践,让你的应用更「动听」
Pourquoi Google Search ne peut - il pas Pager indéfiniment?
fpm工具安装
R|mapping. seq()
如何回答让面试官无话可说
线上运维要会用哪些运维软件和工具?