ZXING二维码生成中文及空白问题

最近用到二维码生成,网上有很多前人给的例子,就不列举了,我是借鉴此人的博客 用com.google.zxing生成、解析二维码

这里只补充一点关于中文的支持及二维码四周空白的问题,在3.2.0版本中,稍细心点可以看到

 1 public final class MultiFormatWriter implements Writer {
 2 
 3   @Override
 4   public BitMatrix encode(String contents,
 5                           BarcodeFormat format,
 6                           int width,
 7                           int height) throws WriterException {
 8     return encode(contents, format, width, height, null);
 9   }
10 
11   @Override
12   public BitMatrix encode(String contents,
13                           BarcodeFormat format,
14                           int width, int height,
15                           Map<EncodeHintType,?> hints) throws WriterException {
16 ...}
MultiFormatWriter class

 

encoder的方法重载中的参数'Map<EncodeHintType,?> hints' 可以重定义一些设置。

Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.MARGIN, 0);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
View Code

 

这样就可以生成出无空白且支持中文的二维码了。

 

代码和前人的类似

 1 public class GoogleBarcodeTest {
 2 
 3     private static final int BLACK = 0xff000000;
 4     private static final int WHITE = 0xFFFFFFFF;
 5 
 6     @Test
 7     public void test() {
 8         Map<EncodeHintType, Object> hints = new HashMap<>();
 9         hints.put(EncodeHintType.MARGIN, 0);
10         hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
11         try {
12 
13             String str = "516030114072545000157500";
14             str = "中文不乱码 :)";
15             String path = "D://test.png";
16             BitMatrix byteMatrix;
17             byteMatrix = new MultiFormatWriter().encode(str, BarcodeFormat.QR_CODE, 200, 200, hints);
18             File file = new File(path);
19             writeToFile(byteMatrix, "png", file);
20         } catch (Exception e) {
21             e.printStackTrace();
22         }
23     }
24 
25     public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
26         BufferedImage image = toBufferedImage(matrix);
27         ImageIO.write(image, format, file);
28     }
29 
30     public static BufferedImage toBufferedImage(BitMatrix matrix) {
31         int width = matrix.getWidth();
32         int height = matrix.getHeight();
33         BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_ARGB);
34         for (int x = 0; x < width; x++) {
35             for (int y = 0; y < height; y++) {
36                 image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
37             }
38         }
39         return image;
40     }
41 
42 }
Test code

 

posted @ 2016-06-08 14:05  名字只是个称号而已  阅读(1427)  评论(0编辑  收藏  举报