使用QRCode.jar进行二维码的生成与解码;
本文非原创,参考网上找来的资料;
package com.wxthtf.iot.common;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import javax.imageio.ImageIO;
import org.apache.log4j.Logger;
import com.swetake.util.Qrcode;
import java.io.*;
import jp.sourceforge.qrcode.QRCodeDecoder;
import jp.sourceforge.qrcode.data.QRCodeImage;
/**
* <li>Title: TwoDivCodeGenerator.java</li>
* <li>Project: AnyIOT</li>
* <li>Package: com.wxthtf.test</li>
* <li>Description: </li>
* <li>Copyright: Copyright (c) 2012</li>
* <li>Company: wxthtf Technologies </li>
* <li>Created on Feb 10, 2012 8:41:06 AM</li>
*
* @author chun_chang
* @version 1.0.0.0
*
*/
public class TwoDivCodeGenerator{
private static String code = "UTF-8";
private static final Logger log = Logger.getLogger(TwoDivCodeGenerator.class);
/**
* 描述:imgGenerate
* @param srcStr
* @param imgName 全文件名,如C:\\aaa.png
* @param widths
* @param heights
* @return
* @CreateOn Feb 10, 2012 9:37:56 AM
* @author chun_chang
*/
public static boolean imgGenerate(String srcStr, String imgName) {
try {
Qrcode qrcode = new Qrcode();
qrcode.setQrcodeErrorCorrect('H');//LMQH
qrcode.setQrcodeEncodeMode('B');
qrcode.setQrcodeVersion(0);//0-15
byte[] d = srcStr.getBytes(code);
boolean[][] b = qrcode.calQrcode(d);
int widths = b.length * 3 + 4;
int heights = b.length * 3 + 4;
BufferedImage bi = new BufferedImage(widths, heights, BufferedImage.TYPE_INT_RGB);
Graphics2D g = bi.createGraphics();
g.setBackground(Color.WHITE);
g.setColor(Color.BLACK);
g.clearRect(0, 0, widths, heights);
if(d.length > 0 && d.length < 1000) {
for(int i = 0; i < b.length; i++) {
for(int j = 0; j < b.length; j++) {
if(b[j][i]) {
g.fillRect(j * 3 + 2, i * 3 + 2, 3, 3);
}
}
}
} else {
log.error("二维码字符串过长");
}
g.dispose();
bi.flush();
String imgType = imgName.substring(imgName.lastIndexOf('.') + 1, imgName.length());
File f = new File(imgName);
ImageIO.write(bi, imgType, f);
return true;
} catch(Exception e) {
log.error(e, e);
return false;
}
}
public static String decoderImg(String fileName) {
QRCodeDecoder decoder = new QRCodeDecoder();
File imageFile = new File(fileName);
BufferedImage image = null;
String str = "";
try {
image = ImageIO.read(imageFile);
str = new String(decoder.decode(new J2SEImage(image)), code);
} catch(Exception e) {
e.printStackTrace();
}
return str;
}
public static void main(String[] args) throws Exception {
String testString = "清华同方";
String fileName = "C:\\123.png";
TwoDivCodeGenerator.imgGenerate(testString, fileName);
String str = TwoDivCodeGenerator.decoderImg(fileName);
System.out.println(str);
}
}
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);
}
}