二维码生成解析

package com.main.util;

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.QRCodeReader;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import org.apache.commons.lang3.StringUtils;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import static redis.clients.jedis.Protocol.CHARSET;

/**
 * @author 
 * @description     二维码生成工具类
 * @time 2018/7/21 10:02
 */
public class QRCodeUtil {
    private static final int QRCOLOR = 0xFF000000; // 默认是黑色
    private static final int BGWHITE = 0xFFFFFFFF; // 背景颜色

    private static final int WIDTH = 400; // 二维码宽
    private static final int HEIGHT = 400; // 二维码高

    private static final String imageFormat = "jpg";         // 图片格式


    // 用于设置QR二维码参数
    private static Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>() {
        private static final long serialVersionUID = 1L;
        {
//            L级:约可纠错7%的数据码字
//            M级:约可纠错15%的数据码字
//            Q级:约可纠错25%的数据码字
//            H级:约可纠错30%的数据码字
//            纠错能力越高,存储的数据就越少
            put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);// 设置QR二维码的纠错级别(H为最高级别)具体级别信息
            put(EncodeHintType.CHARACTER_SET, "utf-8");// 设置编码方式
            put(EncodeHintType.MARGIN, 0);      //生成条码的时候使用,指定边距,单位像素,受格式的影响
        }
    };


    public static void main(String[] args) throws WriterException, IOException {
        File logoFile = new File("D:\\favicon.png");
        File QrCodeFile = new File("D:\\qrCodeFile.png");
        String url = "https://www.baidu.com/";
        drawLogoQRCode(logoFile, QrCodeFile, url);
        createQrCode(new FileOutputStream(new File("d:\\qrcode.jpg")),"你好");
        readQrCode(new FileInputStream(new File("D:\\20180723160320.jpg")));
    }

    // 生成带logo的二维码图片logo路径,生成后的路径,生成内容,图片显示后的内容
    public static void drawLogoQRCode(File logoFile, File codeFile, String contents) {
        try {
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            // 参数顺序分别为:编码内容,编码类型,生成图片宽度,生成图片高度,设置参数
            BitMatrix bm = multiFormatWriter.encode(contents, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            BufferedImage image = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB);

            // 开始利用二维码数据创建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);
                }
            }

//            彩色二维码
//            for (int x = 0; x < WIDTH; x++) {
//                for (int y = 0; y < HEIGHT; y++) {
//                    if(bm.get(x,y)){
//                        if(x<WIDTH/2&&y<HEIGHT/2){
//                            image.setRGB(x, y, 0xFF0094FF);// 蓝色
//                        }else if(x<WIDTH/2&&y>HEIGHT/2){
//                            image.setRGB(x, y, 0xFFFED545);// 黄色
//                        }else if(x>WIDTH/2&&y>HEIGHT/2){
//                            image.setRGB(x, y, 0xFF5ACF00);// 绿色
//                        }else {
//                            image.setRGB(x, y, 0xFF000000);// 黑色
//                        }
//                    }else {
//                        image.setRGB(x, y, 0xffffffff);// 白色
//                    }
//                }
//            }

            int width = image.getWidth();
            int height = image.getHeight();
            if (null!=logoFile && logoFile.exists()) {
                // 构建绘图对象
                Graphics2D g = image.createGraphics();
                // 读取Logo图片
                BufferedImage logo = ImageIO.read(logoFile);
                // 开始绘制logo图片
                g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
                //绘制边框
                BasicStroke stroke = new BasicStroke(5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
                // 设置笔画对象
                g.setStroke(stroke);
                //  指定弧度的圆角矩形
//                RoundRectangle2D.Float round=new RoundRectangle2D.Float(width*2/5,height*2/5,width/5,height/5,20,20);
//                        g.setColor(Color.lightGray);
//                //  回执圆形矩形
//                g.draw(round);

//                //  设置logo有一道灰色边框
//                BasicStroke stroke1=new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
//                //  设置笔画对象
//                g.setStroke(stroke1);
//                RoundRectangle2D.Float round1=new RoundRectangle2D.Float(width*2/5+2,height*2/5+2,width/5-4,height/5-4,20,20);
//                g.setColor(new Color(128,128,128));
//                g.draw(round1);

                g.dispose();
                logo.flush();
            }

            image.flush();

            ImageIO.write(image, imageFormat , codeFile); 
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 生成包含字符串信息的二维码图片
     * @param outputStream 文件输出流路径
     * @param content 二维码携带信息
     */
    public static void createQrCode(OutputStream outputStream, String content){
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        //创建比特矩阵(位矩阵)的QR码编码的字符串
        BitMatrix byteMatrix = null;
        try {
            //`编码内容,编码方式(二维码,条形码),宽度,高度,编码参数设置
            byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            // 使BufferedImage勾画QRCode  (matrixWidth 是行二维码像素点)
            int matrixWidth = byteMatrix.getWidth();
            BufferedImage image = new BufferedImage(matrixWidth-200, matrixWidth-200, BufferedImage.TYPE_INT_RGB);
            image.createGraphics();
            Graphics2D graphics = (Graphics2D) image.getGraphics();
            graphics.setColor(Color.WHITE);
            graphics.fillRect(0, 0, matrixWidth, matrixWidth);
            // 使用比特矩阵画并保存图像
            graphics.setColor(Color.BLACK);
            for (int i = 0; i < matrixWidth; i++){
                for (int j = 0; j < matrixWidth; j++){
                    if (byteMatrix.get(i, j)){
                        graphics.fillRect(i-100, j-100, 1, 1);
                    }
                }
            }
             ImageIO.write(image, imageFormat, outputStream);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    /**
     * 解析二维码
     */
    public static void readQrCode(InputStream inputStream){
        //从输入流中获取字符串信息
        BufferedImage image = null;
        try {
            image = ImageIO.read(inputStream);
        } catch (IOException e) {
            e.printStackTrace();
        }
        //将图像转换为二进制位图源
        LuminanceSource source = new BufferedImageLuminanceSource(image);
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));        //  解码的图像
        Map<DecodeHintType,Object> hints = new LinkedHashMap<DecodeHintType,Object>();      //解码的参数
        // 解码设置编码方式为:utf-8,
        hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
        //优化识别率,为了准确性花费更长的时间,识别速度会变慢
        hints.put(DecodeHintType.TRY_HARDER, Boolean.TRUE);
        //图像是一个纯粹的黑白图像的条形码
//        hints.put(DecodeHintType.PURE_BARCODE, Boolean.TRUE);
        //  图像是哪几种编码格式,List或BarcodeFormat类型
        hints.put(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE);
        QRCodeReader reader = new QRCodeReader();
        Result result = null ;
        try {
            result = reader.decode(bitmap,hints);
            System.out.println("二维码文本内容"+result.getText());
            System.out.println("二维码格式类型:"+result.getBarcodeFormat());
            System.out.println("解析结果:"+result.toString());
        } catch (ReaderException e) {
            e.printStackTrace();
        }
    }
}

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值