1、支持QRcode、ZXing 二维码生成、解析;
2、QRCode 方式生成二维码支持添加图片,如下:
- package common;
-
- 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.util.HashMap;
- import java.util.Map;
-
- import javax.imageio.ImageIO;
-
- import jp.sourceforge.qrcode.QRCodeDecoder;
- import jp.sourceforge.qrcode.exception.DecodingFailedException;
-
- import com.google.zxing.BarcodeFormat;
- import com.google.zxing.Binarizer;
- import com.google.zxing.BinaryBitmap;
- import com.google.zxing.EncodeHintType;
- import com.google.zxing.LuminanceSource;
- import com.google.zxing.MultiFormatReader;
- import com.google.zxing.MultiFormatWriter;
- import com.google.zxing.NotFoundException;
- import com.google.zxing.WriterException;
- import com.google.zxing.common.BitMatrix;
- import com.google.zxing.common.HybridBinarizer;
- import com.swetake.util.Qrcode;
-
-
-
-
-
-
-
-
- public class QRCodeUtil {
-
-
- private static final int BLACK = 0xFF000000;
-
- private static final int WHITE = 0xFFFFFFFF;
-
-
-
-
-
-
-
-
-
- public static void zxingCodeCreate(String text, int width, int height, String outPutPath, String imageType){
- Map<EncodeHintType, String> his = new HashMap<EncodeHintType, String>();
-
- his.put(EncodeHintType.CHARACTER_SET, "utf-8");
- try {
-
- BitMatrix encode = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, width, height, his);
-
-
- int codeWidth = encode.getWidth();
- int codeHeight = encode.getHeight();
-
-
- BufferedImage image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);
- for (int i = 0; i < codeWidth; i++) {
- for (int j = 0; j < codeHeight; j++) {
-
- image.setRGB(i, j, encode.get(i, j) ? BLACK : WHITE);
- }
- }
- File outPutImage = new File(outPutPath);
-
- if(!outPutImage.exists())
- outPutImage.createNewFile();
-
- ImageIO.write(image, imageType, outPutImage);
- } catch (WriterException e) {
- e.printStackTrace();
- System.out.println("二维码生成失败");
- } catch (IOException e) {
- e.printStackTrace();
- System.out.println("生成二维码图片失败");
- }
- }
-
-
-
-
-
-
-
- @SuppressWarnings({ "rawtypes", "unchecked" })
- public static Object zxingCodeAnalyze(String analyzePath) throws Exception{
- MultiFormatReader formatReader = new MultiFormatReader();
- Object result = null;
- try {
- File file = new File(analyzePath);
- if (!file.exists())
- {
- return "二维码不存在";
- }
- BufferedImage image = ImageIO.read(file);
- LuminanceSource source = new LuminanceSourceUtil(image);
- Binarizer binarizer = new HybridBinarizer(source);
- BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
- Map hints = new HashMap();
- hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
- result = formatReader.decode(binaryBitmap, hints);
- } catch (NotFoundException e) {
- e.printStackTrace();
- }
- return result;
- }
-
-
-
-
-
-
-
-
- public static void QRCodeCreate(String content, String imgPath, int version, String logoPath){
- try {
- Qrcode qrcodeHandler = new Qrcode();
-
- qrcodeHandler.setQrcodeErrorCorrect('M');
-
- qrcodeHandler.setQrcodeEncodeMode('B');
-
- qrcodeHandler.setQrcodeVersion(version);
-
- int imgSize = 67 + 12 * (version - 1) ;
- byte[] contentBytes = content.getBytes("gb2312");
- BufferedImage bufImg = new BufferedImage(imgSize , imgSize ,BufferedImage.TYPE_INT_RGB);
- Graphics2D gs = bufImg.createGraphics();
- gs.setBackground(Color.WHITE);
- gs.clearRect(0, 0, imgSize , imgSize);
-
- gs.setColor(Color.BLACK);
-
- int pixoff = 2;
-
- if (contentBytes.length > 0 && contentBytes.length < 130) {
- boolean[][] codeOut = qrcodeHandler.calQrcode(contentBytes);
- for (int i = 0; i < codeOut.length; i++) {
- for (int j = 0; j < codeOut.length; j++) {
- if (codeOut[j][i]) {
- gs.fillRect(j * 3 + pixoff, i * 3 + pixoff, 3, 3);
- }
- }
- }
- } else {
- System.err.println("QRCode content bytes length = " + contentBytes.length + " not in [ 0,130 ]. ");
- }
-
- if(logoPath != null){
- File icon = new File(logoPath);
- if(icon.exists()){
- int width_4 = imgSize / 4;
- int width_8 = width_4 / 2;
- int height_4 = imgSize / 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);
- gs.dispose();
- bufImg.flush();
- }else{
- System.out.println("Error: login图片还在在!");
- }
-
- }
-
-
- gs.dispose();
- bufImg.flush();
-
- File imgFile = new File(imgPath);
- if(!imgFile.exists())
- imgFile.createNewFile();
-
- String imgType = imgPath.substring(imgPath.lastIndexOf(".") + 1, imgPath.length());
-
- ImageIO.write(bufImg, imgType, imgFile);
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
-
-
-
-
-
-
- public static String QRCodeAnalyze(String codePath) {
- File imageFile = new File(codePath);
- BufferedImage bufImg = null;
- String decodedData = null;
- try {
- if(!imageFile.exists())
- return "二维码不存在";
- bufImg = ImageIO.read(imageFile);
-
- QRCodeDecoder decoder = new QRCodeDecoder();
- decodedData = new String(decoder.decode(new ImageUtil(bufImg)), "gb2312");
- } catch (IOException e) {
- System.out.println("Error: " + e.getMessage());
- e.printStackTrace();
- } catch (DecodingFailedException dfe) {
- System.out.println("Error: " + dfe.getMessage());
- dfe.printStackTrace();
- }
- return decodedData;
- }
-
- }
-
-
- 3、最后贴测试代码:
-
- package test;
-
- import java.awt.image.BufferedImage;
- import java.io.InputStream;
- import java.net.URL;
-
- import javax.imageio.ImageIO;
-
- import common.ImageUtil;
- import common.QRCodeUtil;
-
- import jp.sourceforge.qrcode.QRCodeDecoder;
-
-
-
-
-
-
-
-
- public class QRCodeTest {
-
- public static void main(String[] args) throws Exception {
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
-
- System.out.println("success");
- }
- }
Jar 包下载地址:
http://download.csdn.NET/download/u014266877/9716662
3: 使用BarCode4j生成条形码和二维码
BarCode4j网址:http://sourceforge.NET/projects/barcode4j/
barcode4j是使用datamatrix的二维码生成算法,为支持qr的算法
datamatrix是欧美的标准,qr为日本的标准,
barcode4j一般生成出来是长方形的
如:88777alec000yan
这个博客这方面说的挺清楚的:
http://baijinshan.iteye.com/blog/1004554
4:google chart api就有实现二维码的方法
利用这个api,使用google appengine进行实现。
5:JS生成二维码
使用jQuery-qrcode生成二维码
先简单说一下jQuery-qrcode,这个开源的三方库(可以从https://github.com/jeromeetienne/jquery-qrcode 获取),
qrcode.js 是实现二维码数据计算的核心类,
jquery.qrcode.js 是把它用jquery方式封装起来的,用它来实现图形渲染,其实就是画图(支持canvas和table两种方式)
支持的功能主要有:
Js代码:
- text : "https://github.com/jeromeetienne/jquery-qrcode" //设置二维码内容
Js代码:
- render : "canvas",
- width : 256,
- height : 256,
- typeNumber : -1,
- correctLevel : QRErrorCorrectLevel.H,
- background : "#ffffff",
- foreground : "#000000"
使用方式非常简单
Js代码:
- jQuery('#output').qrcode({width:200,height:200,correctLevel:0,text:content});
经过简单实践,
使用canvas方式渲染性能还是非常不错的,但是如果用table方式,性能不太理想,特别是IE9以下的浏览器,所以需要自行优化一下渲染table的方式,这里就不细述了。
其实上面的js有一个小小的缺点,就是默认不支持中文。
这跟js的机制有关系,jquery-qrcode这个库是采用 charCodeAt() 这个方式进行编码转换的,
而这个方法默认会获取它的 Unicode 编码,一般的解码器都是采用UTF-8, ISO-8859-1等方式,
英文是没有问题,如果是中文,一般情况下Unicode是UTF-16实现,长度2位,而UTF-8编码是3位,这样二维码的编解码就不匹配了。
解决方式当然是,在二维码编码前把字符串转换成UTF-8,具体代码如下:
- 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;
- }