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 strWidth1 = outg.getFontMetrics().stringWidth(note1);
                int strWidth2 = outg.getFontMetrics().stringWidth(note2);
                outg.drawString(note1, 200 - strWidth1 / 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 - strWidth2 / 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());
    }
}

转载于:https://my.oschina.net/u/1763091/blog/3101310

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值