您的位置:首页 > 编程语言 > Java开发

二维码生成器和解析器-java

2014-04-28 10:53 176 查看
  1.工具zxing2.1----下载地址:http://code.google.com/p/zxing/downloads/detail?name=ZXing-2.1.zip&can=2&q=

    所有版本下载地址:http://code.google.com/p/zxing/downloads/list

  2.需要的jar包,zxing的core.jar和zxing的javase.jar这两个jar包在zxing2.1版本中地址是

    zxing/zxingorg/web/WEB-INF/lib里能找得到

  代码

private static final int BLACK = 0xff000000;
private static final int WHITE = 0xFFFFFFFF;
public static void main(String[] args) throws Exception {
File file = new File("f://test.png");
TestImg test = new TestImg();
test.encode("duwenlei", file,BarcodeFormat.QR_CODE, 200, 200, null);
test.decode(file);
}

public void encode(String contents, File file, BarcodeFormat format,
int width, int height, Map<EncodeHintType, ?> hints) throws Exception {
BitMatrix bitMatrix =  new MultiFormatWriter().encode(contents, format, width, height);
writeToFile(bitMatrix, "png", file);
}
/**
* 生成二维码图片<br>
*
* @param matrix
* @param format
*            图片格式
* @param file
*            生成二维码图片位置
* @throws IOException
*/
public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
BufferedImage image = toBufferedImage(matrix);
ImageIO.write(image, format, file);
}

/**
* 生成二维码内容<br>
*
* @param matrix
* @return
*/
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) == true ? BLACK : WHITE);
}
}
return image;
}

/**
* 解析QRCode二维码
*/
@SuppressWarnings("unchecked")
public void decode(File file) {
try {
BufferedImage image;
try {
image = ImageIO.read(file);
if (image == null) {
System.out.println("Could not decode image");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
@SuppressWarnings("rawtypes")
Hashtable hints = new Hashtable();
//解码设置编码方式为:utf-8
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
result = new MultiFormatReader().decode(bitmap, hints);
String resultStr = result.getText();
System.out.println("解析后内容:" + resultStr);
} catch (IOException ioe) {
System.out.println(ioe.toString());
} catch (ReaderException re) {
System.out.println(re.toString());
}
} catch (Exception ex) {
System.out.println(ex.toString());
}
}


摘自:/article/4667605.html
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: