使用zxing.jar在线生成二维码。返回base64字符串

本文介绍如何使用Zxing库生成二维码,并提供了一个实用工具类,支持生成不同尺寸的二维码及带logo的二维码,同时返回二维码的Base64编码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

导入Zxing依赖

Gradle

    // https://mvnrepository.com/artifact/com.google.zxing/core google
    implementation group: 'com.google.zxing', name: 'core', version: '3.4.0'

    // https://mvnrepository.com/artifact/com.google.zxing/javase
    implementation group: 'com.google.zxing', name: 'javase', version: '3.4.0'

Maven

<!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.4.0</version>
</dependency>
<!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.4.0</version>
</dependency>


生成二维码工具类

/**
         *
         * @param content               二维码中需要包含的数据,如:content=https://www.baidu.com/
         * @return              返回base64编码格式的二维码,前端只需要将base64编码转成图片即可
         */
        public static String GenerateQRcode(String content) throws IOException, WriterException {
                QRCodeWriter qrCodeWriter = new QRCodeWriter();
                //设置二维码生成内容、格式、宽度、高度
                BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 600, 600);

                ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
                MatrixToImageWriter.writeToStream(bitMatrix, "png", outputStream);

                Base64.Encoder encoder = Base64.getEncoder();

                return encoder.encodeToString(outputStream.toByteArray());
        }

加强工具类,支持返回base64,生成的二维码附带图片

package com.mosukj.util;

import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.codec.binary.Base64;
import org.apache.commons.codec.binary.Base64OutputStream;
import org.springframework.util.Base64Utils;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map;

/**
 * @author xu
 * @Description
 * @createTime 2021年04月12日 15:37:00
 */
public class zxingUtil {


        public static final String QRCODE_DEFAULT_CHARSET = "UTF-8";

        public static final int QRCODE_DEFAULT_HEIGHT = 1000;

        public static final int QRCODE_DEFAULT_WIDTH = 1000;

        private static final int BLACK = 0xFF000000;
        private static final int WHITE = 0xFFFFFFFF;
        public static void main(String[] args) throws IOException, NotFoundException {
            String data = "二维码需要携带的数据";
//            String data = "https://www.baidu.com";

            File logoFile = new File("logo文件地址");
            BufferedImage image = zxingUtil.createQRCodeWithLogo(data, logoFile);

            ByteArrayOutputStream stream = new ByteArrayOutputStream();
            ImageIO.write(image, "png", stream);
            String s = Base64Utils.encodeToString(stream.toByteArray());
            System.out.println(s);
        }

        /**
         * 通过默认设置创建一个二维码
         *
         * @author x
         * @param data
         * @return 缓存图片流
         */
        public static BufferedImage createQRCode(String data) {
            return createQRCode(data, QRCODE_DEFAULT_WIDTH, QRCODE_DEFAULT_HEIGHT);
        }

        /**
         * 通过默认字符集创建一个二维码
         *
         * @author x
         * @param data
         * @param 宽度
         * @param 高度
         * @return
         */
        public static BufferedImage createQRCode(String data, int width, int height) {
            return createQRCode(data, QRCODE_DEFAULT_CHARSET, width, height);
        }

        /**
         * 通过指定字符集创建二维码
         *
         * @author x
         * @param data
         * @param charset
         * @param width
         * @param height
         * @return
         */
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public static BufferedImage createQRCode(String data, String charset, int width, int height) {
            Map hint = new HashMap();
            hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hint.put(EncodeHintType.CHARACTER_SET, charset);

            return createQRCode(data, charset, hint, width, height);
        }

        /**
         * 选择指定的解析方式创建二维码
         *
         * @author x
         * @param data
         * @param charset
         * @param hint
         * @param width
         * @param height
         * @return
         */
        public static BufferedImage createQRCode(String data, String charset, Map<EncodeHintType, ?> hint, int width,
                                                 int height) {
            BitMatrix matrix;
            try {
                matrix = new MultiFormatWriter().encode(new String(data.getBytes(charset), charset), BarcodeFormat.QR_CODE,
                        width, height, hint);
                return toBufferedImage(matrix);
            } catch (WriterException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }
        public static BufferedImage toBufferedImage(BitMatrix matrix) {
            int width = matrix.getWidth();
            int height = matrix.getHeight();
            BufferedImage image = new BufferedImage(width, height,
                    BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < width; x++) {
                for (int y = 0; y < height; y++) {
                    image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
                }
            }
            return image;
        }
        /**
         * 创建一个默认设置带logo的二维码
         *
         * @author x
         * @param data
         * @param logoFile
         * @return
         */
        public static BufferedImage createQRCodeWithLogo(String data, File logoFile) {
            return createQRCodeWithLogo(data, QRCODE_DEFAULT_WIDTH, QRCODE_DEFAULT_HEIGHT, logoFile);
        }

        /**
         * 通过默认字符集和带logo创建一个二维码
         *
         * @author x
         * @param data
         * @param width
         * @param height
         * @param logoFile
         * @return
         */
        public static BufferedImage createQRCodeWithLogo(String data, int width, int height, File logoFile) {
            return createQRCodeWithLogo(data, QRCODE_DEFAULT_CHARSET, width, height, logoFile);
        }

        /**
         * 创建一个指定字符集和带logo的二维码
         *
         * @author x
         * @param data
         * @param charset
         * @param width
         * @param height
         * @param logoFile
         * @return
         */
        @SuppressWarnings({ "unchecked", "rawtypes" })
        public static BufferedImage createQRCodeWithLogo(String data, String charset, int width, int height, File logoFile) {
            Map hint = new HashMap();
            hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hint.put(EncodeHintType.CHARACTER_SET, charset);

            return createQRCodeWithLogo(data, charset, hint, width, height, logoFile);
        }

        /**
         * 选择解析方式和指定的logo创建二维码
         *
         * @author x
         * @param data
         * @param charset
         * @param hint
         * @param width
         * @param height
         * @param logoFile
         * @return
         */
        public static BufferedImage createQRCodeWithLogo(String data, String charset, Map<EncodeHintType, ?> hint,
                                                         int width, int height, File logoFile) {
            try {
                BufferedImage qrcode = createQRCode(data, charset, hint, width, height);
                BufferedImage logo = ImageIO.read(logoFile);
                int deltaHeight = height - logo.getHeight();
                int deltaWidth = width - logo.getWidth();

                BufferedImage combined = new BufferedImage(height, width, BufferedImage.TYPE_INT_ARGB);
                Graphics2D g = (Graphics2D) combined.getGraphics();
                g.drawImage(qrcode, 0, 0, null);
                g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
                g.drawImage(logo, (int) Math.round(deltaWidth / 2), (int) Math.round(deltaHeight / 2), null);

                return combined;
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }

        /**
         * 将缓存图片流转base64
         *
         * @author x
         * @param image
         * @return
         */
        public static String getImageBase64String(BufferedImage image) {
            String result = null;
            try {
                ByteArrayOutputStream os = new ByteArrayOutputStream();
                OutputStream b64 = new Base64OutputStream(os);
                ImageIO.write(image, "png", b64);
                result = os.toString("UTF-8");
            } catch (UnsupportedEncodingException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            }
            return result;
        }

        /**
         * Decode the base64Image data to image
         *
         * @author stefli
         * @param base64ImageString
         * @param file
         */
        public static void convertBase64StringToImage(String base64ImageString, File file) {
            FileOutputStream os;
            try {
                Base64 d = new Base64();
                byte[] bs = d.decode(base64ImageString);
                os = new FileOutputStream(file.getAbsolutePath());
                os.write(bs);
                os.close();
            } catch (FileNotFoundException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (IOException e) {
                throw new RuntimeException(e.getMessage(), e);
            } catch (Exception e) {
                throw new RuntimeException(e.getMessage(), e);
            }
        }


}

如果对你有帮助的话,请支持以下笔者吧。也可以前往主页看看其他文章,也许对你有帮助❤️❤️❤️

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

languageStudents

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值