javase 生成二维码 (一)
最近突然对二维码长生兴趣,查了下资料发现一个开源资料交 Zxing ,用它可以很方便的进行二维码的生成和开发
它支持多种码型的生成和解析,包括一维码和二维码
支持码型:
|
|
|
|
支持多种开发平台,包括android,ios 也至此在网页上、jsp上生成二维码。
相关开发包下载地址:http://code.google.com/p/zxing/
虽然提供了源码但是貌似没有很好的帮助文档,至少我没找到,有线索的同学希望能告诉我一声。
下面写一个生成二维码的小程序。在书写之前在工程中需要导入javase.jar和core.jar
程序如下:
1 import java.io.File; 2 import com.google.zxing.BarcodeFormat; 3 import com.google.zxing.MultiFormatWriter; 4 import com.google.zxing.client.j2se.MatrixToImageWriter; 5 import com.google.zxing.common.BitMatrix; 6 7 8 public class Encoding { 9 10 /** 11 * 编码 12 * @param contents 13 * @param width 14 * @param height 15 * @param imgPath 16 */ 17 public void encode(String contents, int width, int height, String imgPath) { 18 /* Map<Object, Object> hints = new HashMap<Object, Object>(); 19 // 指定纠错等级 20 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L); 21 // 指定编码格式 22 hints.put(EncodeHintType.CHARACTER_SET, "GBK"); */ 23 try { 24 BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, 25 BarcodeFormat.QR_CODE, width, height); 26 27 MatrixToImageWriter 28 .writeToFile(bitMatrix, "png", new File(imgPath)); 29 30 } catch (Exception e) { 31 e.printStackTrace(); 32 } 33 } 34 35 /** 36 * @param args 37 */ 38 public static void main(String[] args) { 39 String imgPath = "e:/test.png"; 40 String contents = "Hello World!" 41 + "firsttest!" ; 43 int width = 300, height = 300; 44 Encoding handler = new Encoding(); 45 handler.encode(contents, width, height, imgPath); 46 47 System.out.println("create already!."); 48 } 49 50 }
参考资料:http://sjsky.iteye.com/blog/1142177
应为参考资料中的程序是在1.6版的Zxing中生成的二维码所以encoding方法中的参数有所改变。
最后的生成的图片存储在imgPath 指定的路径下。
后面将尽力对这个源码进行解析下,作为一个新手来说压力有点大⊙﹏⊙b汗。并且也会更行一些解码的程序。
ps:当二维码中包含中文时需要设置编码方式才能使之正确显示。而且需要用小写的“utf-8”或者“gbk”什么的