zxing和QRCode 生成解析二维码

zxing和QRCode都是用来生成和解析二维码的工具

QRCode:是有日本Demso公司于1994年研制的一种矩阵二维码符号码

zxing:老美的(个人更喜欢这个)

桌面或Web应用建议采用QRCode,Android应用建议采用zxing

不说废话,直接来

1.QRCode

引入maven (我引入了依赖后没办法在线下载这个包,只好自己去下载jar包后,放到本地maven库,然后再maven依赖导入)

这里放一个QRCode.jar的链接(内含使用教程)

<dependency>
     <groupId>QRCode</groupId>
     <artifactId>QRCode</artifactId>
     <version>3.0</version>
</dependency>

QRCode工具类(传进logo的参数有值就是生成带logo的二维码,传入logo参数为空值的就是生成不带logo的二维码)

package com.liqiye.springbootdemo.utils;
 
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.UnsupportedEncodingException;

import javax.imageio.ImageIO;

import com.swetake.util.Qrcode;
import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.data.QRCodeImage;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author liqiye
 * @description QRCode二维码工具类 ,实现输入字符串(文本,网址)生成对应的二维码二维码,具有4个等级的容错能力
 * @date 2019/4/13
 */
public class QRCodeUtils {

	private static final Logger log = LoggerFactory.getLogger(QRCodeUtils.class);

	/**
	 * 二维码可包含的内容
	 */
	public class EncodeMode{

		// N代表的是数字
		public final static char N = 'N';

		// A代表的是a-z
		public final static char A= 'A';

		// B代表的是其他字符
		public final static char B = 'B';
	}
	
	/**
	 * 二维码的容错能力等级
	 * 二维码容错率用字母表示,容错能力等级分为:L、M、Q、H四级
	 * 二维码具有容错功能,当二维码图片被遮挡一部分后,仍可以扫描出来。
	 * 容错的原理是二维码在编码过程中进行了冗余,就像是123被编码成123123,这样只要扫描到一部分二维码图片,
	 * 二维码内容还是可以被全部读到。
	 * 二维码容错率即是指二维码图标被遮挡多少后,仍可以被扫描出来的能力。容错率越高,则二维码图片能被遮挡的部分越多。
	 */
	public class ErrorCorrect{

		// 低,最大 7% 的错误能够被纠正
		public final static char L = 'L';

		// 中,最大 15% 的错误能够被纠正
		public final static char M = 'M';

		// 中上,最大 25% 的错误能够被纠正
		public final static char Q = 'Q';

		// 高,最大 30% 的错误能够被纠正
		public final static char H = 'H';
	}
	
	/**
	 * 基于 QRCode 生成二维码
	 * @param content 要写入二维码的内容
	 * @param savePath 完整的保存路径
	 * @param version 版本
	 * @param logoPath 完整的logo路径,如果为null或者"",就是不设置logo
	 * @return 是否生成二维码图片成功
	 */
	public static boolean createQRCode(String content, String savePath, int version, String logoPath){
		// 创建生成二维码的对象
        Qrcode qrcode = new Qrcode();
        // 设置二维码的容错能力等级
        qrcode.setQrcodeErrorCorrect(ErrorCorrect.M);
        // N代表的是数字,A代表的是a-z,B代表的是其他字符
        qrcode.setQrcodeEncodeMode(EncodeMode.B);
        // 版本
        qrcode.setQrcodeVersion(version);
        // 设置验证码的大小
        int width = 67 + 12 * (version - 1);
        int height = 67 + 12 * (version - 1);
        // 定义缓冲区图片
        BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        // 设置画图工具
        Graphics2D gs = bufferedImage.createGraphics();
        // 设置二维码背景颜色
        gs.setBackground(Color.white);//lightGray
        // 设置颜色
        gs.setColor(Color.black);//cyan,green,red,black,pink
        // 清除画板内容
        gs.clearRect(0, 0, width, height);
        // 定义偏移量
        int pixoff = 2;
 
        // 填充的内容转化为字节数
        byte[] ctt;
		try {
			ctt = content.getBytes("utf-8");
			// 设置编码方式
	        if (ctt.length > 0 && ctt.length < 120) {
	            boolean[][] s = qrcode.calQrcode(ctt);
	            for (int i = 0; i < s.length; i++) {
	                for (int j = 0; j < s.length; j++) {
	                    if (s[j][i]) {
	                        // 验证码图片填充内容
	                        gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
	                    }
	                }
	            }
	        }
	        /* 判断是否需要添加logo图片 */
            if(logoPath != null && !"".equals(logoPath)){
                File icon = new File(logoPath);
                if(icon.exists()){
                    int width_4 = width / 4;
                    int width_8 = width_4 / 2;
                    int height_4 = height / 4;
                    int height_8 = height_4 / 2;
                    Image img = ImageIO.read(icon);
                    gs.drawImage(img, width_4 + width_8, height_4 + height_8,width_4,height_4, null);
                }else{
                    System.out.println("Error: login图片不存在!");
                    log.info("Error: login图片不存在!");
					return false;
                }
            }
	        // 结束写入
	        gs.dispose();
	        // 结束内存图片
	        bufferedImage.flush();
	        // 保存生成的二维码图片
	        ImageIO.write(bufferedImage, "png", new File(savePath));
	        return true;
		} catch (Exception e) {
			e.printStackTrace();
		}
		return false;
	}

	/**
	 * 解析QRCode二维码(输入图片地址)
	 * @param filePath 二维码图片的路径
	 * @return 二维码内容
	 */
	public static String readQRCode(String filePath){
		File file = new File(filePath);
		//读取图片到缓冲区
		BufferedImage bufferedImage = null;
		try {
			bufferedImage = ImageIO.read(file);
		} catch (IOException e) {
			e.printStackTrace();
			log.info("读取二维码文件失败");
		}
		//QRCode解码器
		QRCodeDecoder codeDecoder = new QRCodeDecoder();
		//通过解析二维码获得信息
		String result = null;
		try {
			result = new String(codeDecoder.decode(new MyQRCodeImage(bufferedImage)), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			log.info("解析二维码失败");
		}
		return result;
	}

	/**
	 * 解析QRCode二维码(输入图片字节流)
	 * @param input 二维码图片的字节流
	 * @return
	 */
	public static String readQRCode(InputStream input){
		BufferedImage bufferedImage = null;
		try {
			bufferedImage = ImageIO.read(input);
		} catch (IOException e) {
			e.printStackTrace();
			log.info("读取二维码字节流失败");
		}
		//QRCode解码器
		QRCodeDecoder codeDecoder = new QRCodeDecoder();
		//通过解析二维码获得信息
		String result = null;
		try {
			result = new String(codeDecoder.decode(new MyQRCodeImage(bufferedImage)), "utf-8");
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
			log.info("解析二维码失败");
		}
		return result;
	}

}

class MyQRCodeImage implements QRCodeImage {

	BufferedImage bufferedImage;

	public MyQRCodeImage(BufferedImage bufferedImage) {
		this.bufferedImage = bufferedImage;
	}

	//宽
	@Override
	public int getWidth() {
		return bufferedImage.getWidth();
	}

	//高
	@Override
	public int getHeight() {
		return bufferedImage.getHeight();
	}

	//颜色
	@Override
	public int getPixel(int i, int j) {
		return bufferedImage.getRGB(i, j);
	}
}

后面一起测试

2.zxing

引入maven(com.google.zxing.javase已经包含了com.google.zxing.core,会自动引入)

 <dependency>
      <groupId>com.google.zxing</groupId>
      <artifactId>javase</artifactId>
      <version>3.3.0</version>
</dependency>

zxing工具类(传进logo的参数有值就是生成带logo的二维码,传入logo参数为空值的就是生成不带logo的二维码)

package com.liqiye.springbootdemo.utils;

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.decoder.ErrorCorrectionLevel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;

import static com.google.zxing.client.j2se.MatrixToImageConfig.WHITE;
import static jp.sourceforge.qrcode.util.Color.BLACK;

/**
 * @author liqiye
 * @description zxing二维码工具类
 * @date 2019/4/13
 */
public class ZxingUtils {

    private static final Logger log = LoggerFactory.getLogger(ZxingUtils.class);

    private static int WIDTH=300;
    private static int HEIGHT=300;
    private static String FORMAT="png";//二维码格式

    /**
     * 生成二维码
     * @param content 要写入二维码的内容
     * @param savePath 完整的保存路径
     * @param logoPath 完整的logo路径,如果为null或者"",就是不设置logo
     * @return 是否生成二维码图片成功
     */
    public static boolean createQRCode(String content, String savePath, String logoPath){
        //定义二维码参数
        Map hints=new HashMap();
        hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//设置编码
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.Q);//设置容错等级
        hints.put(EncodeHintType.MARGIN, 2);//设置边距默认是5
        BufferedImage bufferedImage = new BufferedImage(WIDTH, HEIGHT, BufferedImage.TYPE_INT_RGB); // 定义缓冲区图片
        Graphics2D g = (Graphics2D) bufferedImage.getGraphics(); // 设置画图工具

        try {
            // zxing的官方类
            BitMatrix bitMatrix=new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, WIDTH, HEIGHT, hints);
            BufferedImage image = new BufferedImage(bitMatrix.getWidth(), bitMatrix.getHeight(), BufferedImage.TYPE_INT_RGB);
            for (int x = 0; x < bitMatrix.getWidth(); x++) {
                for (int y = 0; y < bitMatrix.getHeight(); y++) {
                    image.setRGB(x, y, bitMatrix.get(x, y) ? BLACK : WHITE);
                }
            }
            g.drawImage(image, 0, 0, null); // 生成二维码
            // 判断是否需要添加logo图片
            if(logoPath != null && !"".equals(logoPath)) {
                File icon = new File(logoPath);
                if (!icon.exists()) {
                    log.info("Error: login图片不存在!");
                    return false;
                }else{
                    BufferedImage logo = null;
                    logo = ImageIO.read(icon);
                    int width_4 = WIDTH / 4;
                    int width_8 = width_4 / 2;
                    int height_4 = HEIGHT / 4;
                    int height_8 = height_4 / 2;
                    g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 1f));
                    g.drawImage(logo, width_4 + width_8, height_4 + height_8,width_4,height_4, null);
                }
            }
            // 结束写入
            g.dispose();
            // 结束内存图片
            bufferedImage.flush();
            // 保存生成的二维码图片
            ImageIO.write(bufferedImage, "png", new File(savePath));
            /*Path path = new File(savePath).toPath();
            MatrixToImageWriter.writeToPath(bitMatrix, FORMAT, path); //写到指定路径下*/
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("生成二维码失败");
            return false;
        }
    }

    /**
     * 解析二维码(输入图片地址)
     * @param filePath 二维码图片的路径
     * @return 二维码内容
     */
    public static Result readQrCode(String filePath){
        // zxing的官方类
        MultiFormatReader reader = new MultiFormatReader();
        File file = new File(filePath);
        try {
            BufferedImage image = ImageIO.read(file);
            BinaryBitmap binaryBitmap=new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
            Map hints=new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//设置编码
            Result result = reader.decode(binaryBitmap,hints);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析二维码失败");
            return null;
        }
    }

    /**
     * 解析二维码(输入图片字节流)
     * @param input 二维码图片的字节流
     * @return 二维码内容
     */
    public static Result readQrCode(InputStream input){
        // zxing的官方类
        MultiFormatReader reader = new MultiFormatReader();
        try {
            BufferedImage image = ImageIO.read(input);
            BinaryBitmap binaryBitmap=new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
            Map hints=new HashMap();
            hints.put(EncodeHintType.CHARACTER_SET, "utf-8");//设置编码
            Result result = reader.decode(binaryBitmap,hints);
            return result;
        } catch (Exception e) {
            e.printStackTrace();
            log.info("解析二维码失败");
            return null;
        }
    }

}

3.测试

package com.liqiye.springbootdemo.test;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.Result;
import com.liqiye.springbootdemo.utils.QRCodeUtils;
import com.liqiye.springbootdemo.utils.ZxingUtils;
import org.junit.Test;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;

/**
 * @author liqiye
 * @description 测试QRCode生成二维码
 * @date 2019/4/13
 */
public class QRCodeTest {

    // QRCode生成二维码
    @Test
    public void test1() {
        String content = "http://www.baidu.com/";
        String savePath = "F:/qrcode.png";
        int version = 9;
        String logoPath = "F:/weixin.png";
        boolean result = QRCodeUtils.createQRCode(content, savePath, version, logoPath);
        if (result){
            System.out.println("\n二维码图片生成成功!");
        }else{
            System.out.println("\n二维码图片生成失败!");
        }
    }

    // QRCode解析二维码
    @Test
    public void test2() throws FileNotFoundException {
        String filePath = "F:/qrcode.png";
        File file = new File(filePath);
        FileInputStream fileInputStream = new FileInputStream(file);
        String s = QRCodeUtils.readQRCode(fileInputStream);
        System.out.println("获取二维码信息:"+s);
    }

    // zxing生成二维码
    @Test
    public void test3(){
        String content = "http://www.baidu.com/";
        String savePath = "F:/qrcode.png";
        String logoPath = "F:/weixin.png";
        boolean result = ZxingUtils.createQRCode(content, savePath,logoPath);
        if (result){
            System.out.println("\n二维码图片生成成功!");
        }else{
            System.out.println("\n二维码图片生成失败!");
        }
    }

    // zxing解析二维码
    @Test
    public void test4() throws FileNotFoundException {
        String filePath = "F:/qrcode.png";
        File file = new File(filePath);
        FileInputStream fileInputStream = new FileInputStream(file);
        Result result = ZxingUtils.readQrCode(fileInputStream);
        // 解析结果
        String content = result.toString();
        // 二维码格式
        BarcodeFormat barcodeFormat = result.getBarcodeFormat();
        // 二维码文本内容
        String text = result.getText();
        System.out.println("解析结果:"+content);
        System.out.println("二维码格式:"+barcodeFormat);
        System.out.println("二维码文本内容:"+text);
    }


}

总结:两种工具的使用方法也没差多少,生成的二维码样子都点区别,根据需求选用把

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值