zxing生成二維碼設置邊框顏色


真是研究了很久很久,滿滿的淚啊


zxing生成二維碼,默認是可以增加空白邊框的,但是並沒有可以設置邊框顏色的屬性。

其中增加空白邊框的屬性的一句話是:

Map hints = new HashMap();
hints.put(EncodeHintType.MARGIN, 1);


使用這句話設置邊框,留出來的邊框的顏色,就是二維碼中主顏色的以外的那個顏色。通常主顏色都是黑色,背景色都是白色。如下二維碼的邊框的顏色,就是除了綠色以外的那個顏色。

 


所以並沒有設置邊框顏色的屬性,那該怎么辦?
比如:要求使用POI把二維碼放到Excel中,但是不能占了Excel的邊框,而是要內嵌進去。
剛開始做出來的效果是:

最后需要修改成的效果是:


最后找到的解決方案是,重寫它的方法:MatrixToImageWriter.toBufferedImage(bitMatrix);

頁面的調用點為:

1 MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
2 Map hints = new HashMap();
3 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
4 hints.put(EncodeHintType.MARGIN, "0");
5 hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
6 BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, 100, 100, hints);
7 BufferedImage qrPic = null;
8 qrPic = MatrixToImageWriter.toBufferedImage(bitMatrix);

 

初始方法為:

 1 public static BufferedImage toBufferedImage(BitMatrix matrix) {
 2   int width = matrix.getWidth();
 3   int height = matrix.getHeight();
 4   BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
 5   for (int x = 0; x < width; x++) {
 6     for (int y = 0; y < height; y++) {
 7       image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
 8     }
 9   }
10   return image;
11 }

 

重寫后為: 

 1 public static BufferedImage toBufferedImageCustom(BitMatrix matrix) {
 2 //二維碼邊框的寬度,默認二維碼的寬度是100,經過多次嘗試后自定義的寬度
 3   int left = 3;
 4   int right = 4;
 5   int top = 2;
 6   int bottom = 2;
 7 
 8 //1、首先要自定義生成邊框
 9   int[] rec = matrix.getEnclosingRectangle();   //獲取二維碼圖案的屬性
10   int resWidth = rec[2] + left + right;
11   int resHeight = rec[3] + top + bottom;
12 
13   BitMatrix matrix2 = new BitMatrix(resWidth, resHeight); // 按照自定義邊框生成新的BitMatrix
14   matrix2.clear();
15   for(int i=left+1; i < resWidth-right; i++){   //循環,將二維碼圖案繪制到新的bitMatrix中
16     for(int j=top+1; j < resHeight-bottom; j++){
17       if(matrix.get(i-left + rec[0], j - top + rec[1])){
18         matrix2.set(i,j);
19       }
20     }
21   }
22 
23   int width = matrix2.getWidth();
24   int height = matrix2.getHeight();
25 
26 //2、為邊框設置顏色
27   BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
28   for (int x = 0; x < width; x++) {
29     for (int y = 0; y < height; y++) {
30       if(x<left || x> width-right|| y< top || y>height-bottom){
31         image.setRGB(x, y,BLACK);    //為了與Excel邊框重合,設置二維碼邊框的顏色為黑色
32       }else{
33         image.setRGB(x, y, matrix2.get(x, y) ? BLACK : WHITE);
34       }
35     }
36   }
37   return image;
38 }

 原創文章,歡迎轉載,轉載請注明出處!


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM