码迷,mamicode.com
首页 > 其他好文 > 详细

通过QRCode生成二维码与解码

时间:2015-01-01 01:26:32      阅读:321      评论:0      收藏:0      [点我收藏+]

标签:

先决条件:

  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();
?}

}
}
?

通过QRCode生成二维码与解码

标签:

原文地址:http://www.cnblogs.com/codesir/p/4196893.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!