首先引入zxing用于生成二维码
<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.3</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.3.3</version>
</dependency>
直接上代码
package com.fdj;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* 二维码以及图片合成工具类
*
* @author wysnxzm
*/
public class ZxingUtils {
/**
* 生成二维码
*
* @param contents 二维码内容
* @param width 图片宽度
* @param height 图片高度
* @param hints 二维码相关参数
* @return BufferedImage对象
* @throws WriterException 编码时出错
* @throws IOException 写入文件出错
*/
public static BufferedImage enQRCode(String contents, int width, int height, Map<EncodeHintType, ?> hints) throws WriterException {
// String uuid = UUID.randomUUID().toString().replace("-", "");
//本地完整路径
// String pathname = path + "/" + uuid + "." + format;
//生成二维码
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
// Path file = new File(pathname).toPath();
//将二维码保存到路径下
// MatrixToImageWriter.writeToPa(bitMatrix, format, file);
// return pathname;
return MatrixToImageWriter.toBufferedImage(bitMatrix);
}
public static BufferedImage enQRCode(String contents, int width, int height) throws WriterException {
//定义二维码参数
Map<EncodeHintType, Object> hints = new HashMap<>();
//编码
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
//容错级别
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//边距
hints.put(EncodeHintType.MARGIN, 0);
return enQRCode(contents, width, height, hints);
}
/**
* 将图片绘制在背景图上
*
* @param backgroundImage 背景图
* @param zxingImage 图片
* @param x 图片在背景图上绘制的x轴起点
* @param y 图片在背景图上绘制的y轴起点
* @return
* @throws IOException
*/
public static BufferedImage drawImage(BufferedImage backgroundImage, BufferedImage zxingImage, int x, int y) throws IOException {
Objects.requireNonNull(backgroundImage, ">>>>>背景图不可为空");
Objects.requireNonNull(zxingImage, ">>>>>二维码不可为空");
//二维码宽度+x不可以超过背景图的宽度,长度同理
if ((zxingImage.getWidth() + x) > backgroundImage.getWidth() || (zxingImage.getHeight() + y) > backgroundImage.getHeight()) {
throw new IOException(">>>>>二维码宽度+x不可以超过背景图的宽度,长度同理");
}
//合并图片
Graphics2D g = backgroundImage.createGraphics();
g.drawImage(zxingImage, x, y,
zxingImage.getWidth(), zxingImage.getHeight(), null);
return backgroundImage;
}
public static BufferedImage drawImage(String backgroundPath, BufferedImage zxingImage, int x, int y) throws IOException {
//读取背景图的图片流
BufferedImage backgroundImage;
//Try-with-resources 资源自动关闭,会自动调用close()方法关闭资源,只限于实现Closeable或AutoCloseable接口的类
try (InputStream imagein = new FileInputStream(backgroundPath)) {
backgroundImage = ImageIO.read(imagein);
}
return drawImage(backgroundImage, zxingImage, x, y);
}
/**
* 将文字绘制在背景图上
*
* @param backgroundImage 背景图
* @param x 文字在背景图上绘制的x轴起点
* @param y 文字在背景图上绘制的y轴起点
* @return
* @throws IOException
*/
public static BufferedImage drawString(BufferedImage backgroundImage, String text, int x, int y, Font font, Color color) {
//绘制文字
Graphics2D g = backgroundImage.createGraphics();
//设置颜色
g.setColor(color);
//消除锯齿状
g.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_LCD_HRGB);
//设置字体
g.setFont(font);
//绘制文字
g.drawString(text, x, y);
return backgroundImage;
}
/**
* backgroundImage 转换为输出流
*
* @param backgroundImage 图片流
* @param format 图片后缀
* @return
* @throws IOException
*/
public static InputStream bufferedImageToInputStream(BufferedImage backgroundImage, String format) throws IOException {
ByteArrayOutputStream bs = new ByteArrayOutputStream();
try (
ImageOutputStream
imOut = ImageIO.createImageOutputStream(bs)) {
ImageIO.write(backgroundImage, format, imOut);
InputStream is = new ByteArrayInputStream(bs.toByteArray());
return is;
}
}
public static InputStream bufferedImageToInputStream(BufferedImage backgroundImage) throws IOException {
return bufferedImageToInputStream(backgroundImage, "png");
}
/**
* 保存为文件
*
* @param is 输入流
* @param fileName 保存的图片路径和文件名
* @throws IOException
*/
public static void saveFile(InputStream is, String fileName) throws IOException {
try (BufferedInputStream in = new BufferedInputStream(is);
BufferedOutputStream out = new BufferedOutputStream(new FileOutputStream(fileName))) {
int len;
byte[] b = new byte[1024];
while ((len = in.read(b)) != -1) {
out.write(b, 0, len);
}
}
}
public static void main(String[] args) {
//二维码宽度
int width = 293;
//二维码高度
int height = 293;
//二维码内容
String contcent = "http://baidu.com";
BufferedImage zxingImage = null;
try {
//二维码图片流
zxingImage = ZxingUtils.enQRCode(contcent, width, height);
} catch (WriterException e) {
e.printStackTrace();
}
//背景图片地址
String backgroundPath = "C:/Users/Admin/Desktop/background_en.png";
InputStream inputStream = null;
try {
//合成二维码和背景图
BufferedImage image = ZxingUtils.drawImage(backgroundPath, zxingImage, 224, 754);
//绘制文字
//读取本地字体
//Font font = new Font("default", Font.BOLD, 35);
//读取自定义物理字体
Font font = Font.createFont(Font.TRUETYPE_FONT,new File("C:\\Windows\\Fonts\\courbd.ttf")).deriveFont(Font.BOLD).deriveFont(40f);
//文字内容
String text = "17000中文😊😊😊";
image = ZxingUtils.drawString(image, text, 325, 700,font,new Color(244,254,189));
//图片转inputStream
inputStream = ZxingUtils.bufferedImageToInputStream(image);
} catch (Exception e) {
e.printStackTrace();
}
//保存的图片路径
String originalFileName = "C:/Users/Admin/Desktop/99999.png";
try {
//保存为本地图片
ZxingUtils.saveFile(inputStream, originalFileName);
} catch (IOException e) {
e.printStackTrace();
}
}
}
代码对应资源下载(包括背景图):https://download.csdn.net/download/wysnxzm/10739117
服务器字体文件(非必须):https://download.csdn.net/download/wysnxzm/11350788
可展示emoji表情符号的字体文件:https://download.csdn.net/download/wysnxzm/11637203 该字体会导致中文乱码,暂时没有解决方案
2021年3月30日 19:38:03 实际上默认微软雅黑就支持中文和emoji同时显示,但是Font.createFont()的读取方式存在问题所以导致乱码,改成new Font(“C:\Windows\Fonts\msyhbd.ttc”, Font.BOLD, 35)获取字体即可
2021年3月30日 21:28:36 增加注释,增加默认字体重载方法
2021年3月31日 12:18:07 new Font()方法存在误导,填写字体路径实际上读取失败使用的是Dialog(本地默认字体)目前只在windows10上实现中文和emoji共同绘制,linux还在研究中
2021年3月31日 14:48:01 首先看资料:物理字体和逻辑字体 之前测试成功是因为win10上的逻辑字体可以同时解析中文和emoji,但是linux的逻辑字体与win10不同所以会失效,new Font(“C:\Windows\Fonts\msyhbd.ttc”, Font.BOLD, 35)不是读取到了微软雅黑而是解析成了Dialog的逻辑字体,最终结论与18年写这篇文章的保持一致:无法使用单个字体同时解析中文和emoji
2021年3月31日 15:01:44 使用多个字体绘制一段文字 算是一个能实现的方案吧
2021年3月31日 23:25:29 找到了可以完美实现的方案-合并字体,将中文和emoji字体合并即可
下载链接:黑体+emoji|微软雅黑+emoji