生成二维码两种方法

1、使用前端jquery.qrcode.min.js框架生成二维码

    在https://github.com/jeromeetienne/jquery-qrcode上下载对应的夹包,生成二维码的JSP页面如下:

<%@ page language="java" contentType="text/html; charset=UTF-8"
	pageEncoding="UTF-8"%>




生成二维码






	

	

生成二维码


2、使用后端的zxing夹包生成二维码

    在GitHub上面有开源项目https://github.com/zxing/,下载到本地后解压缩,将core和javase文件夹中的所有.java文件拷贝到Java项目中,然后export为zxing.jar的夹包,作为项目的引用。

生成二位码的源码如下:

public class Genarate2DCode {   
	public static void main(String[] args) throws Exception {
		//二维码宽度
		int width=300;
		//二维码高度
		int height=300;
		//二维码图片格式
		String format="png";
		//二维码内容,这里为VCard规范,可以保存个人名片信息
		String contents=
				"BEGIN:VCARD"+"\n"
		        +"VERSION:2.1"+"\n"
				+"N:姓;名"+"\n"
				+"FN:姓名"+"\n"
				+"NICKNAME:昵称"+"\n"
				+"ORG:公司;部门"+"\n"
				+"TITLE:职位"+"\n"
				+"TEL;WORK;VOICE:工作电话"+"\n"
				+"TEL;HOME;VOICE:家庭电话"+"\n"
				+"TEL;CELL;VOICE:移动电话"+"\n"				
				+"ROLE:职称"+"\n"
				+"ADR;WORK:门牌号;街道;福田;深圳;广东;30314;国家"+"\n"				
				+"ADR;HOME:门牌号;街道;盐田;深圳;广东;30314;国家"+"\n"
				+"EMAIL;PREF;INTERNET:邮箱地址"+"\n"	
				+"URL:https://www.baidu.com"+"\n"
				+"BDAY:出生日期"+"\n"
				+"PHOTO;VALUE=uri:https://timgsa.baidu.com/timg?xxxx"+"\n"
				+"REV:20080424T195243Z"+"\n"
				+"END:VCARD";
		
		//定义二维码参数的哈希映射表
		HashMap hints=new HashMap();
		//编码方式,支持中文
		hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
		//容错等级
		hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
		//二维码边距
		hints.put(EncodeHintType.MARGIN, 1);
		//生成点阵
		BitMatrix bitMatrix=new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height,hints);
		Path file=new File("E:/Img.png").toPath();
		MatrixToImageWriter.writeToPath(bitMatrix, format, file);		
	}	
}


  二维码扫描结果为:

生成二维码两种方法_第1张图片


识别二维码的源码如下:

public class ReadQRCode {
	public static void main(String[] args) throws Exception {
		MultiFormatReader multiFormatReader = new MultiFormatReader();

		File file = new File("E:/Img.png");
		BufferedImage image = ImageIO.read(file);
		BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
		
		// 定义二维码参数的哈希映射表
		HashMap hints = new HashMap();
		// 编码方式,支持中文
		hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
                //输出识别结果
		Result result = multiFormatReader.decode(binaryBitmap, hints);
		System.out.println(result);

	}

}


   

你可能感兴趣的:(java)