首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 软件管理 > 软件架构设计 >

QR二维验证码的生成及判别

2012-08-17 
QR二维验证码的生成及识别package com.testimport java.awt.Colorimport java.awt.Graphics2Dimport ja

QR二维验证码的生成及识别

package com.test;

import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import com.swetake.util.Qrcode;

public class QRCodeEncoderTest {
?public static void main(String[] args) throws Exception{
??QRCodeEncode("TestQRCode.jpg","jpg","测试数据,字符长度不能超过123");
?}
?public static void QRCodeEncode(String filename,String filetype,String input)throws Exception
?{
??Qrcode qrcode = new Qrcode();
??qrcode.setQrcodeErrorCorrect('M');
??qrcode.setQrcodeEncodeMode('B');
??qrcode.setQrcodeVersion(7);

??String testString = input;

??byte[] d = testString.getBytes("GBK");

??BufferedImage bi = new BufferedImage(556, 556,
????BufferedImage.TYPE_INT_RGB);

??// createGraphics???
??Graphics2D g = bi.createGraphics();

??// set background???
??g.setBackground(Color.WHITE);
??g.clearRect(0, 0, 556, 556);

??g.setColor(Color.BLACK);

??if (d.length > 0 && d.length < 123) {
???boolean[][] b = qrcode.calQrcode(d);

???for (int i = 0; i < b.length; i++) {

????for (int j = 0; j < b.length; j++) {
?????if (b[j][i]) {
??????g.fillRect(j * 12 + 2, i * 12 + 2, 12, 12);
?????}
????}

???}
??}

??g.dispose();
??bi.flush();

??String FilePath = filename;
??File f = new File(FilePath);

??ImageIO.write(bi,filetype, f);
??System.out.println("QRCodeEncodeSuccess!");
?}

}

?

?

?

package com.test;

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.UnsupportedEncodingException;

import javax.imageio.ImageIO;

import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.data.QRCodeImage;
import jp.sourceforge.qrcode.exception.DecodingFailedException;

public class QRCodeDecoderTest {
?public static void main(String[] args) {
??String test=QRCodeDecode("2.jpg");
??System.out.println(test);
?}
?public static String QRCodeDecode(String filename)
?{
??QRCodeDecoder decoder = new QRCodeDecoder();

??File imageFile = new File(filename);

??BufferedImage image = null;

??try {
???image = ImageIO.read(imageFile);
??} catch (IOException e) {
???System.out.println("读取文件失败:" + e.getMessage());
??}
??try {

???String decodedData = new String(decoder
?????.decode(new J2SEImage(image)), "GBK");

???return decodedData;
??} catch (DecodingFailedException dfe) {
???System.out.println("解析失败: " + dfe.getMessage());
??} catch (UnsupportedEncodingException e) {
???e.printStackTrace();
??}
??return "";

?}
}

class J2SEImage implements QRCodeImage {
?BufferedImage image;

?public J2SEImage(BufferedImage image) {
??this.image = image;
?}

?public int getWidth() {
??return image.getWidth();
?}

?public int getHeight() {
??return image.getHeight();
?}

?public int getPixel(int x, int y) {
??return image.getRGB(x, y);
?}

}

?

?

用到QRCode.jar包

热点排行