用程序玩玩生成二维码也是挺有意思的,跟大家们分享下java生成二维码的三种方式(生成二维码所需要的jar包我已经传上去了:http://download.youkuaiyun.com/detail/qq_31957747/9740909):
1、用zxing生成二维码
zxing生成二维码的java文件:
CreateQRCode.java
package com.imooc.zxing;
import java.io.File;
import java.nio.file.Path;
import java.util.HashMap;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
//生成二维码
public class CreateQRCode {
public static void main(String[] args) {
int width = 300;
int height = 300;
String format = "png";
String content = "www.baidu.com";
//定义二维码的参数
HashMap hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
//纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
hints.put(EncodeHintType.MARGIN, 2);
//生成二维码
try {
BitMatrix bitMatrix =new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height,hints);
Path file = new File("D:/code/xx.png").toPath();
MatrixToImageWriter.writeToPath(bitMatrix, format, file);
} catch (Exception e) {
e.printStackTrace();
}
}
}
zxing解析二维码的java文件:
ReadQRCode.java
package com.imooc.zxing;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;
import javax.imageio.ImageIO;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.HybridBinarizer;
public class ReadQRCode {
public static void main(String []args){
try {
MultiFormatReader formatReader = new MultiFormatReader();
File file = new File("D:/code/zxing.png");
BufferedImage image = ImageIO.read(file);
BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));
//定义二维码的参数
HashMap hints = new HashMap();
hints.put(EncodeHintType.CHARACTER_SET,"utf-8");
Result result = formatReader.decode(binaryBitmap,hints);
System.out.println("解析结果:"+result.toString());
System.out.println("二维码格式类型:"+result.getBarcodeFormat());
System.out.println("二维码文本内容:"+result.getText());
} catch (NotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
2、用qrcode生成二维码
qrcode生成二维码的java文件:
CreateQRCode.java
package com.imooc.qrcode;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.UnsupportedEncodingException;
import javax.imageio.ImageIO;
import com.swetake.util.Qrcode;
public class CreateQRCode {
public static void main(String[] args) throws Exception {
Qrcode x = new Qrcode();
x.setQrcodeErrorCorrect('M'); //纠错等级
x.setQrcodeEncodeMode('B'); //N代表数字,A代表a-Z,B代表其他字符
x.setQrcodeVersion(7); //版本
String qrData = "www.baidu.com";
int width = 67+12*(7-1);
int height = 67+12*(7-1);
BufferedImage bufferedImage = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
Graphics2D gs = bufferedImage.createGraphics();
gs.setBackground(Color.WHITE);
gs.setColor(Color.BLACK);
gs.clearRect(0, 0, width, height);
int pixoff = 2;//偏移量
byte []d = qrData.getBytes("GB2312");
if(d.length>0 && d.length<120){
boolean [][]s = x.calQrcode(d);
for(int i=0;i<s.length;i++){
for(int j=0;j<s.length;j++){
if(s[i][j]){
gs.fillRect(i*3+pixoff,j*3+pixoff,3,3);
}
}
}
gs.dispose();
bufferedImage.flush();
ImageIO.write(bufferedImage, "png", new File("D:/code/qrcode.png"));
}
}
}
ReadQRCode.java
package com.imooc.qrcode;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import javax.imageio.ImageIO;
import jp.sourceforge.qrcode.QRCodeDecoder;
public class ReadQRCode {
public static void main(String[] args) throws Exception {
File file = new File("D:/code/qrcode.png");
BufferedImage bufferedImage = ImageIO.read(file);
QRCodeDecoder codeDecoder = new QRCodeDecoder();
String result = new String(codeDecoder.decode(new MYQRCodeImage(bufferedImage)),"utf8");
System.out.println(result);
}
}
MYQRCodeImage.java
package com.imooc.qrcode;
import java.awt.image.BufferedImage;
import jp.sourceforge.qrcode.data.QRCodeImage;
public class MYQRCodeImage implements QRCodeImage {
BufferedImage bufferedImage;
public MYQRCodeImage(BufferedImage bufferedImage){
this.bufferedImage = bufferedImage;
}
@Override
public int getHeight() {
return bufferedImage.getHeight();
}
@Override
public int getPixel(int arg0, int arg1) {
return bufferedImage.getRGB(arg0,arg1);
}
@Override
public int getWidth() {
return bufferedImage.getWidth();
}
}
3、jqueryqrcode生成二维码
jqueryqrcode生成二维码的jsp文件:
qrcode.jsp
<%@ page language="java" contentType="text/html; charset=UTF-8"
pageEncoding="UTF-8"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
<title>jqueryqrcode生成二维码</title>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery.qrcode.min.js"></script>
</head>
<body>
生成的二维码如下:<br/>
<div id="qrcode"></div>
<script type="text/javascript">
//jQuery("#qrcode").qrcode("www.baidu.com");
jQuery("#qrcode").qrcode({width:200,height:200,correctLevel:0,text:utf16to8("www.baidu.com")});
function utf16to8(str) {
var out, i, len, c;
out = "";
len = str.length;
for(i = 0; i < len; i++) {
c = str.charCodeAt(i);
if ((c >= 0x0001) && (c <= 0x007F)) {
out += str.charAt(i);
} else if (c > 0x07FF) {
out += String.fromCharCode(0xE0 | ((c >> 12) & 0x0F));
out += String.fromCharCode(0x80 | ((c >> 6) & 0x3F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
} else {
out += String.fromCharCode(0xC0 | ((c >> 6) & 0x1F));
out += String.fromCharCode(0x80 | ((c >> 0) & 0x3F));
}
}
return out;
}
</script>
</body>
</html>
注意:
1、jqueryqrcode可以使用上面那种注释的,也可以用下面那种设置多个属性
各属性的含义:
text : "https://github.com/jeromeetienne/jquery-qrcode" //设置二维码内容
render : "canvas",//设置渲染方式
width : 256, //设置宽度
height : 256, //设置高度
typeNumber : -1, //计算模式
correctLevel : QRErrorCorrectLevel.H,//纠错等级
background : "#ffffff",//背景颜色
foreground : "#000000" //前景颜色
2、由于jquery-qrcode这个库是采用 charCodeAt() 这个方式进行编码转换的,而这个方法默认会获取它的 Unicode 编码,一般的解码器都是采用UTF-8, ISO-8859-1等方式,英文是没有问题,如果是中文,一般情况下Unicode是UTF-16实现,长度2位,而UTF-8编码是3位,这样二维码的编解码就不匹配了。中文就会乱码,所以用一个utf16to8对其进行处理。
也许有人会问,你这个二维码出来的是文本,那有什么用啊,平时二维码扫出来的不是这么简单的东西吧。
如果要想扫出来的是一个网页,那么就得在content字符串前面加上http://,比如 String content = "http://www.baidu.com",这样扫出来的绝壁就是百度的首页喽!
如果想要扫出来的是一个名片,那么就得修改下content的字符串,用VCard规范,如下图所示。