通过QRCode生成二维码与解码

先决条件:

  1. 需要的JAR包qrcode.jar(官网介绍),直接下载QRCode.jar

将QRCode.jar 加入到Maven库

mvn install:install-file -DgroupId=[包名] -DartifactId=[项目名] -Dversion=[版本号] -Dpackaging=[jar] -Dfile=[jar文件所在路径]

 例子:

 mvn install:install-file -DgroupId=com.swetake -DartifactId=QRCode -Dversion=0.9 -Dpackaging=jar -Dfile=./QRCode.jar

 

package com.jc.de.qr;

/**
* Created by Shylock on 14/12/31.
*/

import com.swetake.util.Qrcode;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;


public class QRCodeFactory {

public static BufferedImage createQRCode(String text,Integer...version) throws UnsupportedEncodingException {
Qrcode qrcode = new Qrcode();
int v = 3;
if (version != null&&version.length!=0) v =version[0];
if (text == null ||text.trim().equals(""))return null;
byte[] content = text.getBytes("utf-8");

boolean[][] codeOut = qrcode.calQrcode(content);
int size = codeOut.length*10+10;

 BufferedImage bufferedImage = new BufferedImage(size,size,BufferedImage.TYPE_INT_RGB);

 Graphics2D graphics = bufferedImage.createGraphics();
 graphics.setBackground(Color.WHITE);
 graphics.clearRect(0, 0, size, size);
 graphics.setColor(Color.BLACK);
if (content.length > 0 && content.length < 120) {
for (int i = 0; i < codeOut.length; i++) {
for (int j = 0; j < codeOut.length; j++) {
if (codeOut[j][i]) {
graphics.fillRect(j * 10 + 5, i * 10 + 5, 10, 10);
 }
}
}
} else {
throw new UnsupportedEncodingException("QRCode content bytes length = " + content.length + " not in [ 0,120 ]. ");
 }
graphics.dispose();
 bufferedImage.flush();
return bufferedImage;
 }
/**
* 方法描述:
*
* @param args
 * @throws UnsupportedEncodingException
*/
 public static void main(String[] args) throws UnsupportedEncodingException {

File imgFile = new File("/Users/Shylock/Desktop/test.png");
// 生成二维码QRCode图片

 try {
//图片格式
 ImageIO.write(createQRCode("http://www.baidu.com",3,600), "png", imgFile);
 Desktop.getDesktop().open(imgFile);
 } catch (IOException e) {
e.printStackTrace();
 }

}
}
 

posted on 2015-01-01 00:28  安生。  阅读(1578)  评论(0编辑  收藏  举报

导航