千家信息网

java中怎么实现生成二维码

发表于:2024-10-28 作者:千家信息网编辑
千家信息网最后更新 2024年10月28日,java中怎么实现生成二维码,很多新手对此不是很清楚,为了帮助大家解决这个难题,下面小编将为大家详细讲解,有这方面需求的人可以来学习下,希望你能有所收获。如果是maven项目要在项目中添加依赖 c
千家信息网最后更新 2024年10月28日java中怎么实现生成二维码

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

如果是maven项目要在项目中添加依赖
   com.google.zxing   javase   3.3.0
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 hints = new HashMap() {        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 decodeHints = new HashMap();            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());    }}

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

二维 二维码 图片 参数 级别 生成 内容 编码 坐标 方式 模块 版本 背景 长度 项目 颜色 UTF-8 别为 帮助 最高 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 金融硕士 软件开发 服务器达芬奇数据库 昌平区网络技术服务直销价 软件开发下载软件 江阴上门软件开发诚信合作 大数据时代网络安全现状 深圳市联创软件开发有限公司 网络安全文明教育新闻稿 网络技术有限公司用英语 江西中小学生网络安全知识 催收说上报央行征信数据库 数据库小程序访问 怎么防止数据库表同时写 手机模拟城市连接服务器失败 服务器插上电源后接显示器没反应 甘泉网络安全宣传 重庆软件开发工时 网络安全高级技术工程师答辩 数据库服务器安全管理系统 宝山区正规网络技术产业化 漯河bim软件开发工程报考条件 湖北时代网络技术服务保障 楚雄互联网科技招生 关于网络安全进校园的建议 怎么启动服务器管理器 无法连接到服务器1302 数据库可以运算吗 泉州互动安全教育展馆软件开发 网络技术应用提前通知 软件开发企业工作内容
0