import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* Created by wjb on 2017/3/7.
* 生成二维码
*/
public class CreateQRcode {
public static void main(String[] args) {
int width = 300;
int height = 300;
String format = "png";
String content = "www.baidu.com";
//下面这个是解决中文乱码的
try {
content = new String(content.getBytes("UTF-8"),"ISO-8859-1");
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
// 定义二维码的参数
Map map = new HashMap();
map.put(EncodeHintType.CHARACTER_SET,"utf-8");
map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
map.put(EncodeHintType.MARGIN,2);
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height);
File file = new File("f:/aaa");
MatrixToImageWriter.writeToFile(bitMatrix,format,file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
上面是生成二维码到F盘,先导入两个JAR包(zxing code 3.2.1 , zxing javase 3.2.1),下面是解析二维码:
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
/**
* Created by wjb on 2017/3/7.
* 解析二维码内容
*/
public class ReadQRcode {
public static void main(String[] args) {
MultiFormatReader multiFormatReader = new MultiFormatReader();
File file = new File("f:/aaa");
try {
BufferedImage bufferedImage = ImageIO.read(file);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));
Map map = new HashMap();
map.put(EncodeHintType.CHARACTER_SET,"utf-8");
Result result = multiFormatReader.decode(binaryBitmap, map);
System.out.println("解析结果:"+result.toString());
System.out.println("二维码类型:"+result.getBarcodeFormat());
} catch (Exception e) {
e.printStackTrace();
}
}
}
还有另一种方式,使用Jquery.qrcode的方式生成
<%@ page contentType="text/html;charset=UTF-8" language="java" %>
<html>
<head>
<title>生成二维码</title>
<script type='text/javascript' src='http://cdn.staticfile.org/jquery/2.1.1/jquery.min.js'></script>
<script type="text/javascript" src="http://cdn.staticfile.org/jquery.qrcode/1.0/jquery.qrcode.min.js"></script>
</head>
<body>
生成的二维码如下:<br/>
<div id="qrcode"/><br/>
<script type="text/javascript">
// 这种是直接写内容,默认大小是256*256,下面的方式是指定大小
// jQuery('#qrcode').qrcode("www.BadKids.com");
jQuery('#qrcode').qrcode({width:200,height:200,correctLevel:0,text:"www.BadKids.com"});
</script>
</body>
</html>