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();
}
// 定義二維碼的參數(shù)
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盤农曲,先導(dǎo)入兩個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.
* 解析二維碼內(nèi)容
*/
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("解析結(jié)果:"+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">
// 這種是直接寫內(nèi)容姨谷,默認大小是256*256谅猾,下面的方式是指定大小
// jQuery('#qrcode').qrcode("www.BadKids.com");
jQuery('#qrcode').qrcode({width:200,height:200,correctLevel:0,text:"www.BadKids.com"});
</script>
</body>
</html>
最后編輯于 :
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者