【Android QR Code】開源項目:ZXing(二)二維碼編碼


准備工作:添加依賴庫core.jar

在Package Explorer選擇導入的項目,右鍵 -> Build Path -> Add External Archives...

選擇zxing/core目錄下的core.jar

 

1、設置編碼內容使用的字符集

Map<EncodeHintType,Object> hints = new EnumMap<EncodeHintType,Object>(EncodeHintType.class);
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
message = convertToUTF8(message);

 

2、編碼

BitMatrix lBitMatrix = new MultiFormatWriter().encode(message, BarcodeFormat.QR_CODE, 200, 200, hints);

類MultiFormatWriter:This is a factory class which finds the appropriate Writer subclass for the BarcodeFormat requested and encodes the barcode with the supplied contents.

調用encode方法編碼,返回一個BitMatrix對象。

類BitMatrix:Represents a 2D matrix of bits. In function arguments below, and throughout the common module, x is the column position, and y is the row position. The ordering is always x, y. The origin is at the top-left. Internally the bits are represented in a 1-D array of 32-bit ints. However, each row begins with a new int. This is done intentionally so that we can copy out a row into a BitArray very efficiently. The ordering of bits is row-major. Within each int, the least significant bits are used first, meaning they represent lower x values. This is compatible with BitArray's implementation.

lBitMatrix僅僅是通過bit來存儲二維碼數據。如果要更直觀地觀察編碼的結果,我們需要利用lBitMatrix來生成圖片。

 

3、生成圖片

首先,我們定義黑色和白色的像素值

    private static final int WHITE = 0xFFFFFFFF;
    private static final int BLACK = 0xFF000000;

然后,根據BitMatrix對象,二維矩陣的值,生成圖片

private Bitmap toBitmap(BitMatrix bitMatrix) {
    int width = bitMatrix.getWidth();
    int height = bitMatrix.getHeight();
    int[] pixels = new int[width * height];
    for (int y = 0; y < height; y++) {
      int offset = y * width;
      for (int x = 0; x < width; x++) {
        pixels[offset + x] = bitMatrix.get(x, y) ? BLACK : WHITE;
      }
    }
    
    Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
    bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
    return bitmap;
}

 

范例項目運行結果:

 

 


免責聲明!

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



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