溫馨提示×

溫馨提示×

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

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

java中怎么實現(xiàn)生成二維碼

發(fā)布時間:2021-06-21 14:40:22 來源:億速云 閱讀:238 作者:Leah 欄目:大數(shù)據(jù)

java中怎么實現(xiàn)生成二維碼,很多新手對此不是很清楚,為了幫助大家解決這個難題,下面小編將為大家詳細講解,有這方面需求的人可以來學習下,希望你能有所收獲。

如果是maven項目要在項目中添加依賴
<dependency>
   <groupId>com.google.zxing</groupId>
   <artifactId>javase</artifactId>
   <version>3.3.0</version>
</dependency>
package com.aigyun.config;


import com.aigyun.constant.StringUtils;
import com.aigyun.entity.DeviceUavInfo;
import com.alibaba.fastjson.JSONObject;
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.swetake.util.Qrcode;
import lombok.extern.slf4j.Slf4j;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.Objects;
import java.util.UUID;

public class QCodeUtil {

    private static final int QRCOLOR = 0xFF000000; // 默認是黑色
    private static final int BGWHITE = 0xFFFFFFFF; // 背景顏色


    // 用于設(shè)置QR二維碼參數(shù)
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;

        {
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 設(shè)置QR二維碼的糾錯級別(H為最高級別)具體級別信息
            put(EncodeHintType.CHARACTER_SET, "utf-8");// 設(shè)置編碼方式
            put(EncodeHintType.MARGIN, 0);
        }
    };

    /**
     * java繪制只包含內(nèi)容的二維碼
     *
     * @param content
     * @param imgPath
     */
    public static void getQrCodeImg(String content, String imgPath) {
        int width = 300;
        int height = 300;

        Qrcode qrcode = new Qrcode();
        qrcode.setQrcodeErrorCorrect('M');  // 設(shè)置糾錯級別(級別有:L(7%) M(15%) Q(25%) H(30%) )
        qrcode.setQrcodeEncodeMode('B'); // 設(shè)置編碼方式
        qrcode.setQrcodeVersion(7); // 設(shè)置二維碼版本(版本有 1-40個,)

        // 1.設(shè)置圖片大小(BufferedImage.TYPE_INT_RGB:利用三原色繪制二維碼)
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D gs = img.createGraphics(); // 創(chuàng)建畫筆
        gs.setBackground(Color.WHITE); // 設(shè)置背景為白色
        gs.clearRect(0, 0, width, height);  // 設(shè)置一個矩形(四個參數(shù)分別為:開始繪圖的x坐標,y坐標,圖片寬,圖片高)
        gs.setColor(Color.BLACK); // 設(shè)置二維碼圖片的顏色
        byte[] bt = null; // 把內(nèi)容轉(zhuǎn)換字節(jié)數(shù)組
        try {
            bt = content.getBytes("UTF-8");
        } catch (UnsupportedEncodingException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }

        int py = 4; // 偏移量
        boolean[][] code = qrcode.calQrcode(bt); // 開始準備畫圖
        for (int i = 0; i < code.length; i++) {
            for (int j = 0; j < code[i].length; j++) {
                if (code[j][i]) {
                    // 四個參數(shù)(畫圖的起始x和y位置,每個小模塊的寬和高(二維碼是有一個一個的小模塊構(gòu)成的));
                    gs.fillRect(j * 6 + py, i * 6 + py, 6, 6);
                }
            }
        }
        // 畫圖
        try {
            ImageIO.write(img, "png", new File(imgPath));
            System.out.println("OK!");
        } catch (IOException e) {
            System.out.println("二維碼異常。。。。。");
            e.printStackTrace();
        }
    }

    public static String decode(String filepath) {
        try {
            BufferedImage bufferedImage = ImageIO.read(new FileInputStream(filepath));
            LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
            BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
            HashMap<DecodeHintType, Object> decodeHints = new HashMap<DecodeHintType, Object>();
            decodeHints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
            Result result = new MultiFormatReader().decode(bitmap, decodeHints);
            return result.getText();
        } catch (NotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

        return null;

    }

    /**
     * zxing生成帶logo的二維碼
     *
     * @param logoFile
     * @param codeFile
     * @param qrUrl
     * @param note
     */
    public static boolean drawLogoQRCode(final File logoFile, File codeFile, final String qrUrl, final String note, final int width, final int height) {
        MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
        BitMatrix bm = null;
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        ;
        try {
            // 參數(shù)順序分別為:編碼內(nèi)容,編碼類型,生成圖片寬度,生成圖片高度,設(shè)置參數(shù)
            bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException we) {
            we.printStackTrace();
            return false;
        }

        // 開始利用二維碼數(shù)據(jù)創(chuàng)建Bitmap圖片,分別設(shè)為黑(0xFFFFFFFF)白(0xFF000000)兩色
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bm.get(x, y) ? QRCOLOR : BGWHITE);
            }
        }

        //繪制圖片
        Graphics2D g = image.createGraphics();
        try {
            BufferedImage logo = ImageIO.read(logoFile);
            g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
            g.dispose();
            logo.flush();
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        // 自定義文本描述
        if (StringUtils.isNotEmpty(note)) {
            // 新的圖片,把帶logo的二維碼下面加上文字
            BufferedImage outImage = new BufferedImage(400, 445, BufferedImage.TYPE_4BYTE_ABGR);
            Graphics2D outg = outImage.createGraphics();
            // 畫二維碼到新的面板
            outg.drawImage(image, 0, 0, image.getWidth(), image.getHeight(), null);
            // 畫文字到新的面板
            outg.setColor(Color.BLACK);
            outg.setFont(new Font("楷體", Font.BOLD, 30)); // 字體、字型、字號
            int strWidth = outg.getFontMetrics().stringWidth(note);
            if (strWidth > 399) {
                //長度過長就截取前面部分
                // 長度過長就換行
                String note1 = note.substring(0, note.length() / 2);
                String note2 = note.substring(note.length() / 2, note.length());
                int strWidth2 = outg.getFontMetrics().stringWidth(note1);
                int strWidth3 = outg.getFontMetrics().stringWidth(note2);
                outg.drawString(note1, 200 - strWidth2 / 2, height + (outImage.getHeight() - height) / 2 + 12);
                BufferedImage outImage2 = new BufferedImage(400, 485, BufferedImage.TYPE_4BYTE_ABGR);
                Graphics2D outg2 = outImage2.createGraphics();
                outg2.drawImage(outImage, 0, 0, outImage.getWidth(), outImage.getHeight(), null);
                outg2.setColor(Color.BLACK);
                outg2.setFont(new Font("宋體", Font.BOLD, 30)); // 字體、字型、字號
                outg2.drawString(note2, 200 - strWidth3 / 2, outImage.getHeight() + (outImage2.getHeight() - outImage.getHeight()) / 2 + 5);
                outg2.dispose();
                outImage2.flush();
                outImage = outImage2;
            } else {
                outg.drawString(note, 200 - strWidth / 2, height + (outImage.getHeight() - height) / 2 + 12); // 畫文字
            }
            outg.dispose();
            outImage.flush();
            image = outImage;
        }

        image.flush();

        try {
            ImageIO.write(image, "png", codeFile); // TODO
        } catch (IOException e) {
            e.printStackTrace();
            return false;
        }

        return true;
    }


    public static void main(String[] args) {

//        JSONObject jsonObject = new JSONObject();
//        jsonObject.put("reg_id", 12123);
//        getQrCodeImg(jsonObject.toJSONString(), "f:/qrcode/test1.jpg");
//        //encode(jsonObject.toJSONString(), "f:/qrcode/test.jpg");
//        File logoFile = new File("f:/qrcode/512x512bb.jpg");
//        File codeFile = new File("f:/qrcode/test.png");
//        drawLogoQRCode(logoFile, codeFile, jsonObject.toJSONString(),"掃一掃查看配置參數(shù)");
//
//        String content = decode("f:/qrcode/test.jpg");
//        System.out.println(content);



        System.out.println(UUID.randomUUID().toString());
    }
}

看完上述內(nèi)容是否對您有幫助呢?如果還想對相關(guān)知識有進一步的了解或閱讀更多相關(guān)文章,請關(guān)注億速云行業(yè)資訊頻道,感謝您對億速云的支持。

向AI問一下細節(jié)

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

AI