千家信息网

Zxing中怎么生成二维码并返回

发表于:2025-12-01 作者:千家信息网编辑
千家信息网最后更新 2025年12月01日,这篇文章给大家介绍Zxing中怎么生成二维码并返回,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。引入 Google Zxing jar包 com.google.zxing
千家信息网最后更新 2025年12月01日Zxing中怎么生成二维码并返回

这篇文章给大家介绍Zxing中怎么生成二维码并返回,内容非常详细,感兴趣的小伙伴们可以参考借鉴,希望对大家能有所帮助。

引入 Google Zxing jar包

    com.google.zxing    core    3.4.0    com.google.zxing    javase    3.4.0

工具类

package com.sunlands.feo.school.candlestick.utils;import com.google.zxing.*;import com.google.zxing.client.j2se.BufferedImageLuminanceSource;import com.google.zxing.common.BitMatrix;import com.google.zxing.common.HybridBinarizer;import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;import org.springframework.stereotype.Component;import javax.imageio.ImageIO;import java.awt.*;import java.awt.geom.RoundRectangle2D;import java.awt.image.BufferedImage;import java.io.File;import java.io.IOException;import java.io.OutputStream;import java.util.Hashtable;/** * @author dongxie */@Componentpublic class QrCodeUtils {    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;    /**     * 创建二维码图片     *     * @param content    内容     * @param logoPath   logo     * @param isCompress 是否压缩Logo     * @return 返回二维码图片     * @throws WriterException e     * @throws IOException     BufferedImage     */    public static BufferedImage createImage(String content, String logoPath, boolean isCompress) throws WriterException, IOException {        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();        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, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);            }        }        if (logoPath == null || "".equals(logoPath)) {            return image;        }        // 插入图片        QrCodeUtils.insertImage(image, logoPath, isCompress);        return image;    }    /**     * 添加Logo     *     * @param source     二维码图片     * @param logoPath   Logo     * @param isCompress 是否压缩Logo     * @throws IOException void     */    private static void insertImage(BufferedImage source, String logoPath, boolean isCompress) throws IOException {        File file = new File(logoPath);        if (!file.exists()) {            return;        }        Image src = ImageIO.read(new File(logoPath));        int width = src.getWidth(null);        int height = src.getHeight(null);        // 压缩LOGO        if (isCompress) {            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();    }    /**     * 生成带Logo的二维码     *     * @param content    二维码内容     * @param logoPath   Logo     * @param destPath   二维码输出路径     * @param isCompress 是否压缩Logo     * @throws Exception void     */    public static void create(String content, String logoPath, String destPath, boolean isCompress) throws Exception {        BufferedImage image = QrCodeUtils.createImage(content, logoPath, isCompress);        mkdirs(destPath);        ImageIO.write(image, FORMAT_NAME, new File(destPath));    }    /**     * 生成不带Logo的二维码     *     * @param content  二维码内容     * @param destPath 二维码输出路径     */    public static void create(String content, String destPath) throws Exception {        QrCodeUtils.create(content, null, destPath, false);    }    /**     * 生成带Logo的二维码,并输出到指定的输出流     *     * @param content    二维码内容     * @param logoPath   Logo     * @param output     输出流     * @param isCompress 是否压缩Logo     */    public static void create(String content, String logoPath, OutputStream output, boolean isCompress) throws Exception {        BufferedImage image = QrCodeUtils.createImage(content, logoPath, isCompress);        ImageIO.write(image, FORMAT_NAME, output);    }    /**     * 生成不带Logo的二维码,并输出到指定的输出流     *     * @param content 二维码内容     * @param output  输出流     * @throws Exception void     */    public static void create(String content, OutputStream output) throws Exception {        QrCodeUtils.create(content, null, output, false);    }    /**     * 二维码解析     *     * @param file 二维码     * @return 返回解析得到的二维码内容     * @throws Exception String     */    public static String parse(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);        return result.getText();    }    /**     * 二维码解析     *     * @param path 二维码存储位置     * @return 返回解析得到的二维码内容     * @throws Exception String     */    public static String parse(String path) throws Exception {        return QrCodeUtils.parse(new File(path));    }    /**     * 判断路径是否存在,如果不存在则创建     *     * @param dir 目录     */    public static void mkdirs(String dir) {        if (dir != null && !"".equals(dir)) {            File file = new File(dir);            if (!file.isDirectory()) {                file.mkdirs();            }        }    }}

使用

package com.jiafly.blueberry.controller;import com.jiafly.blueberry.common.utils.QrCodeUtils;import org.apache.tomcat.util.http.fileupload.IOUtils;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RequestParam;import org.springframework.web.bind.annotation.RestController;import javax.imageio.ImageIO;import javax.imageio.stream.ImageOutputStream;import javax.servlet.http.HttpServletResponse;import java.awt.image.BufferedImage;import java.io.ByteArrayInputStream;import java.io.ByteArrayOutputStream;import java.io.InputStream;import java.io.OutputStream;/** * 二维码 * * @author dongxie */@RestController@RequestMapping(path = "/qrcode")public class QrCodeController {    @GetMapping(path = "/create")    public void image(HttpServletResponse response, @RequestParam("content") String content) {        try {            BufferedImage bufferedImage = QrCodeUtils.createImage(content, null, false);            responseImage(response, bufferedImage);        } catch (Exception e) {            // 异常自行处理,应用程序切忌直接打印堆栈日志,难定位            e.printStackTrace();        }    }    /**     * 设置 可通过postman 或者浏览器直接浏览     *     * @param response      response     * @param bufferedImage bufferedImage     * @throws Exception e     */    public void responseImage(HttpServletResponse response, BufferedImage bufferedImage) throws Exception {        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();        ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);        ImageIO.write(bufferedImage, "jpeg", imageOutput);        InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());        OutputStream outputStream = response.getOutputStream();        response.setContentType("image/jpeg");        response.setCharacterEncoding("UTF-8");        IOUtils.copy(inputStream, outputStream);        outputStream.flush();    }}

关于Zxing中怎么生成二维码并返回就分享到这里了,希望以上内容可以对大家有一定的帮助,可以学到更多知识。如果觉得文章不错,可以把它分享出去让更多的人看到。

二维 二维码 内容 输出 生成 路径 图片 更多 UTF-8 帮助 浏览 不错 位置 兴趣 堆栈 宽度 小伙 小伙伴 尺寸 工具 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 中国澳门定制oa服务器云主机 大章鱼网络技术有限公司 全境封锁香港服务器 服务器内存大的手机游戏 宝卡免流服务器 数据库技术与应用设计报告 g6系统的服务器 伙伴服务器上已存在以下作用域 京颐软件开发工资 手机会员软件开发供应商 计算机三级数据库技术精讲班 200m服务器是千兆网吗 互联网科技知识与创新 原神为何不能自由切换服务器 IC卡设计软件开发 问题不大山东互联网科技有限公司 华为gpu服务器收费标准 青岛信息城服务器组装 c语言软件开发能做哪些 软件开发人员加班制度 奉贤区智能网络技术销售公司 华为泰山服务器信创名录 网络安全反诈措施 干部档案管理系统数据库程序设计 如何在聊天室中加入数据库 中驰车之谷互联网科技 酒店网络安全机器安装 品质好的嵌入式软件开发 国安网络技术怎么样 疫情信息网络安全领导小组
0