java生成二维码(底部添加文字+linux安装微软雅黑)


1. 添加依赖

   <!--        二维码解析工具-->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.3.0</version>
        </dependency>
         <!-- hutool工具包-->
        <dependency>
            <groupId>cn.hutool</groupId>
            <artifactId>hutool-all</artifactId>
            <version>5.4.1</version>
        </dependency>

2. 工具类

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.extra.qrcode.BufferedImageLuminanceSource;
import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.extra.qrcode.QrConfig;
import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.ruoyi.common.config.RuoYiConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.font.FontDesignMetrics;
import sun.misc.BASE64Encoder;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.font.FontRenderContext;
import java.awt.font.LineMetrics;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;

/**
 * @author Ford Wang
 * @Description 生成企业二维码
 */
public class QRCodeUtilEx {

    private static Logger logger = LoggerFactory.getLogger(QRCodeUtilEx.class);
    private static final String CHARSET = "utf-8";
    private static final String FORMAT_NAME = "JPG";
    // 二维码尺寸
    private static final int QRCODE_SIZE = 300;
    // LOGO宽度
    private static final int WIDTH = 60;
    // LOGO高度
    private static final int HEIGHT = 60;
    // 字体大小
    private static final int FONT_SIZE = 18;


    private static BufferedImage createImage(String content, String bottomDes, String imgPath, boolean needCompress) throws Exception {
        Hashtable hints = new Hashtable();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
                hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        int tempHeight = height;
        boolean needDescription = (null != bottomDes && !"".equals(bottomDes));
        if (needDescription) {
            tempHeight += 30;
        }
        BufferedImage image = new BufferedImage(width, tempHeight, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }
        // 插入图片
        if (imgPath != null && !"".equals(imgPath)) {
            QRCodeUtilEx.insertImage(image, imgPath, needCompress);
        }
        //添加底部文字
        if (needDescription) {
            QRCodeUtilEx.addFontImage(image, bottomDes);
        }
        return image;
    }

    /**
     * 添加 底部图片文字
     *
     * @param source      图片源
     * @param declareText 文字本文
     */
    private static void addFontImage(BufferedImage source, String declareText) {
        BufferedImage textImage = strToImage(declareText, QRCODE_SIZE, 50);
        Graphics2D graph = source.createGraphics();
        //开启文字抗锯齿
        graph.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

        int width = textImage.getWidth(null);
        int height = textImage.getHeight(null);

        Image src = textImage;
        graph.drawImage(src, 0, QRCODE_SIZE - 20, width, height, null);
        graph.dispose();
    }

    private static BufferedImage strToImage(String str, int width, int height) {
        BufferedImage textImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = (Graphics2D)textImage.getGraphics();
        //开启文字抗锯齿
        g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);
        g2.setBackground(Color.WHITE);
        g2.clearRect(0, 0, width, height);
        g2.setPaint(Color.BLACK);
        FontRenderContext context = g2.getFontRenderContext();
        Font font = new Font("微软雅黑", Font.BOLD, FONT_SIZE);
        g2.setFont(font);
        LineMetrics lineMetrics = font.getLineMetrics(str, context);
        FontMetrics fontMetrics = FontDesignMetrics.getMetrics(font);
        float offset = (width - fontMetrics.stringWidth(str)) / 2;
        float y = (height + lineMetrics.getAscent() - lineMetrics.getDescent() - lineMetrics.getLeading()) / 2;

        g2.drawString(str, (int)offset, (int)y);

        return textImage;
    }

    private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "   该文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
        if (needCompress) { // 压缩LOGO
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }
            Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
            BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = tag.getGraphics();
            g.drawImage(image, 0, 0, null); // 绘制缩小后的图
            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (QRCODE_SIZE - width) / 2;
        int y = (QRCODE_SIZE - height) / 2;
        graph.drawImage(src, x, y, width, height, null);
        Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    public static void encode(String content, String bottomDes, String imgPath, String destPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtilEx.createImage(content, bottomDes, imgPath, needCompress);
        mkdirs(destPath);
        // String file = new Random().nextInt(99999999)+".jpg";
        // ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));
        ImageIO.write(image, FORMAT_NAME, new File(destPath));
    }
    //获取二维码base64数据
    public static  String encodeStr(String content, String bottomDes) throws Exception{
        BufferedImage image = QRCodeUtilEx.createImage(content, bottomDes, null, false);
        ByteArrayOutputStream baos = new ByteArrayOutputStream();//io流
        ImageIO.write(image, FORMAT_NAME,baos);//写入流中
        byte[] bytes = baos.toByteArray();//转换成字节
        BASE64Encoder encoder = new BASE64Encoder();
        String jpg_base64 = encoder.encodeBuffer(bytes).trim();//转换成base64串
        jpg_base64 = jpg_base64.replaceAll("\n", "").replaceAll("\r", "");//删除 \r\n
        //System.out.println("值为:"+"data:image/jpg;base64,"+png_base64);
        return  jpg_base64;
    }

    public static BufferedImage encode(String content, String bottomDes, String imgPath, boolean needCompress) throws Exception {
        BufferedImage image = QRCodeUtilEx.createImage(content, bottomDes, imgPath, needCompress);
        return image;
    }

    public static void mkdirs(String destPath) {
        File file = new File(destPath);
        // 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
        if (!file.exists() && !file.isDirectory()) {
            file.mkdirs();
        }
    }

    public static void encode(String content, String bottomDes, String imgPath, String destPath) throws Exception {
        QRCodeUtilEx.encode(content, bottomDes, imgPath, destPath, false);
    }
    // 被注释的方法
    /*
     * public static void encode(String content, String destPath, boolean
     * needCompress) throws Exception { QRCodeUtil.encode(content, null, destPath,
     * needCompress); }
     */

    public static void encode(String content, String bottomDes, String destPath) throws Exception {
        QRCodeUtilEx.encode(content, bottomDes, null, destPath, false);
    }

    public static void encode(String content, String bottomDes, String imgPath, OutputStream output, boolean needCompress)
            throws Exception {
        BufferedImage image = QRCodeUtilEx.createImage(content, bottomDes, imgPath, needCompress);
        ImageIO.write(image, FORMAT_NAME, output);
    }

    public static void encode(String content, String bottomDes, OutputStream output) throws Exception {
        QRCodeUtilEx.encode(content, bottomDes, null, output, false);
    }

    public static String decode(File file) throws Exception {
        BufferedImage image;
        image = ImageIO.read(file);
        if (image == null) {
            return null;
        }
        BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        Result result;
        Hashtable hints = new Hashtable();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        String resultStr = result.getText();
        return resultStr;
    }

    public static String decode(String path) throws Exception {
        return QRCodeUtilEx.decode(new File(path));
    }

}

3. 测试类

以下是测试生成二维码的代码:

public class QrcodeTest {
    public static void main(String args[]) {
        try {
        //第一个参数:二维码生成的内容
        //第二个参数:底部显示的文字
        //第三个参数:图片生成路径
         QRCodeUtilEx.encode("360","芜湖众腾人力资源有限公司","D:/ruoyi/uploadPath/upload2021-11-17\1637139164765.jpg");
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

最终生成的二维码:
在这里插入图片描述

解析二维码使用**String decode(File file)**方法

4. 解决线上环境无法在底部添加文字的问题

以上代码在本地(windows)环境下运行最终可得到底部添加上文字的二维码,但部署到线上环境(linux)后生成的二维码底部却没有文字,因为我在工具类设置的底部文字是微软雅黑,查阅资料后发现是线上服务器没有安装微软雅黑的字体包,将字体包安装即可。

1.创建本地字体文件夹:

[root@iz2ze3sd1c5ttsdp4f68xcez qr]~ mkdir /usr/share/fonts/local

2.在C:\Windows\Fonts找到微软雅黑字体,将其通过xftp上传到/usr/share/fonts/local/目录下
在这里插入图片描述
3.修改字体权限,使root以外的用户可以使用这些字体

[root@iz2ze3sd1c5ttsdp4f68xcez qr]~ chmod -R 777 /usr/share/fonts/local

4.建立字体缓存

[root@iz2ze3sd1c5ttsdp4f68xcez qr]~ cd /usr/share/fonts/local
[root@iz2ze3sd1c5ttsdp4f68xcez qr]~ mkfontscale # 若提示command not found 执行yum -y install mkfontscale
[root@iz2ze3sd1c5ttsdp4f68xcez qr]~ mkfontdir
[root@iz2ze3sd1c5ttsdp4f68xcez qr]~ fc-cache -fv #若提示command not found 执行yum -y install fontconfig 

5.查看已安装的中文字体列表

[root@iz2ze3sd1c5ttsdp4f68xcez qr]~ fc-list :lang=zh 

在这里插入图片描述
最后重启项目,再次生成二维码,底部成功添加上文字

评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值