1. 程式人生 > >Android平臺生成二維碼(by google.zxing)

Android平臺生成二維碼(by google.zxing)

查了大部分的資料,發現android平臺下生成二維碼的例子都是使用谷歌的zxing類,因此仿照某一個帖子編寫了一個demo進行測試,仿照的帖子:
https://blog.csdn.net/myname_kk/article/details/77649477
例子中主要用到了BitMatrix,QRCodeWriter兩個類,BitMatrix類物件用來存放文字轉換好的01二進位制陣列,QRCodeWriter類用來把BitMatrix陣列轉成影象
主要的程式碼如下:
QRImageUtil類:封裝QR操作,主要是文字轉二維碼操作

import android.graphics.Bitmap;
import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.WriterException; import java.util.Hashtable; public class QRImageUtil { /* 根據文字內容生成二維碼 */ public
static Bitmap createQRImage(String content, final int width, final int height) { //合法性判斷 if(content == null || "".equals(content) ||content.length() <= 0) { return null; } Hashtable<EncodeHintType, String> hints = new Hashtable<>(); hints.
put(EncodeHintType.CHARACTER_SET, "utf-8"); try { BitMatrix bitMatrix = new QRCodeWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints); int [] pixels = new int [width * height]; for(int y = 0; y < height; y++) { for(int x = 0; x < width; x++) { pixels[y * width + x] = bitMatrix.get(x,y) ? 0xff000000 : 0xffffffff; } } Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888); bitmap.setPixels(pixels, 0, width, 0, 0, width, height); return bitmap; } catch (WriterException ex) { ex.printStackTrace(); } return null; } }

然後,在主介面中,放置文字輸入框,影象控制元件,生成二維碼的按鈕

public class MainActivity extends AppCompatActivity {
    private Button btnGenerate = null;
    private EditText edtContent = null;
    private ImageView imageView = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        edtContent = (EditText)this.findViewById(R.id.editText);
        imageView = (ImageView)this.findViewById(R.id.imgQR);
        //register button callback function
        btnGenerate = (Button)this.findViewById(R.id.generateBtn);
        btnGenerate.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                String txt = edtContent.getText().toString();
                Bitmap bitmap = QRImageUtil.createQRImage(txt, imageView.getWidth(), imageView.getHeight());
                if(bitmap != null) {
                    imageView.setImageBitmap(bitmap);
                }
            }
        });

    }
}

程式執行的效果如下:
在這裡插入圖片描述