温馨提示×

温馨提示×

您好,登录后才能下订单哦!

密码登录×
登录注册×
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》

java中怎么实现生成二维码

发布时间:2021-06-21 14:40:22 来源:亿速云 阅读:221 作者:Leah 栏目:大数据

java中怎么实现生成二维码,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。

如果是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; // 背景颜色


    // 用于设置QR二维码参数
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;

        {
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别(H为最高级别)具体级别信息
            put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
            put(EncodeHintType.MARGIN, 0);
        }
    };

    /**
     * java绘制只包含内容的二维码
     *
     * @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');  // 设置纠错级别(级别有:L(7%) M(15%) Q(25%) H(30%) )
        qrcode.setQrcodeEncodeMode('B'); // 设置编码方式
        qrcode.setQrcodeVersion(7); // 设置二维码版本(版本有 1-40个,)

        // 1.设置图片大小(BufferedImage.TYPE_INT_RGB:利用三原色绘制二维码)
        BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        Graphics2D gs = img.createGraphics(); // 创建画笔
        gs.setBackground(Color.WHITE); // 设置背景为白色
        gs.clearRect(0, 0, width, height);  // 设置一个矩形(四个参数分别为:开始绘图的x坐标,y坐标,图片宽,图片高)
        gs.setColor(Color.BLACK); // 设置二维码图片的颜色
        byte[] bt = null; // 把内容转换字节数组
        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]) {
                    // 四个参数(画图的起始x和y位置,每个小模块的宽和高(二维码是有一个一个的小模块构成的));
                    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 {
            // 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
            bm = multiFormatWriter.encode(qrUrl, BarcodeFormat.QR_CODE, width, height, hints);
        } catch (WriterException we) {
            we.printStackTrace();
            return false;
        }

        // 开始利用二维码数据创建Bitmap图片,分别设为黑(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(),"扫一扫查看配置参数");
//
//        String content = decode("f:/qrcode/test.jpg");
//        System.out.println(content);



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

看完上述内容是否对您有帮助呢?如果还想对相关知识有进一步的了解或阅读更多相关文章,请关注亿速云行业资讯频道,感谢您对亿速云的支持。

向AI问一下细节

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

AI