溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務條款》

Zxing中怎么生成二維碼并返回

發(fā)布時間:2021-07-30 16:42:28 來源:億速云 閱讀:182 作者:Leah 欄目:大數(shù)據(jù)

這篇文章給大家介紹Zxing中怎么生成二維碼并返回,內(nèi)容非常詳細,感興趣的小伙伴們可以參考借鑒,希望對大家能有所幫助。

引入 Google Zxing jar包

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.4.0</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.4.0</version>
</dependency>

工具類

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
 */
@Component
public 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;

    /**
     * 創(chuàng)建二維碼圖片
     *
     * @param content    內(nèi)容
     * @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<EncodeHintType, Object> 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    二維碼內(nèi)容
     * @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  二維碼內(nèi)容
     * @param destPath 二維碼輸出路徑
     */
    public static void create(String content, String destPath) throws Exception {
        QrCodeUtils.create(content, null, destPath, false);
    }

    /**
     * 生成帶Logo的二維碼,并輸出到指定的輸出流
     *
     * @param content    二維碼內(nèi)容
     * @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 二維碼內(nèi)容
     * @param output  輸出流
     * @throws Exception void
     */
    public static void create(String content, OutputStream output) throws Exception {
        QrCodeUtils.create(content, null, output, false);
    }

    /**
     * 二維碼解析
     *
     * @param file 二維碼
     * @return 返回解析得到的二維碼內(nèi)容
     * @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<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        result = new MultiFormatReader().decode(bitmap, hints);
        return result.getText();
    }

    /**
     * 二維碼解析
     *
     * @param path 二維碼存儲位置
     * @return 返回解析得到的二維碼內(nèi)容
     * @throws Exception String
     */
    public static String parse(String path) throws Exception {
        return QrCodeUtils.parse(new File(path));
    }

    /**
     * 判斷路徑是否存在,如果不存在則創(chuàng)建
     *
     * @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中怎么生成二維碼并返回就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細節(jié)

免責聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權請聯(lián)系站長郵箱:is@yisu.com進行舉報,并提供相關證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權內(nèi)容。

AI