LoginSignup
23
25

More than 5 years have passed since last update.

ZXingライブラリでAndroid上でQRコードを作成する

Posted at

外部のQRコード生成APIに頼らずアプリ内でQRコードを作成したかったので、ZXingライブラリを使ってやってみました。

準備

build.gradle のdependenciesに以下の記述を追加します。

dependencies {
    ...
    compile 'com.google.zxing:core:3.2.1' // これを追加
}

QRコードのBitmap作成メソッド

ZXingはAndroidに限らないJava向けの汎用ライブラリなので、Android固有のBitmap等へ変換する箇所は自分で実装する必要があります。
といっても、QRコードの黒く塗るべきドットとそうでないドットはZXingが教えてくれるので、それを使ってBitmapを生成するのは簡単です。

public static Bitmap generateQR(String qrText, int size = 500) throws WriterException {

    // QRコードのビットマトリクスを作成
    QRCode qrCode = Encoder.encode(qrText, ErrorCorrectionLevel.H);
    ByteMatrix byteMatrix = qrCode.getMatrix();

    // QRコードのサイズのBitmapを作成
    Bitmap bitmap = Bitmap.createBitmap(byteMatrix.getWidth(), byteMatrix.getHeight(), Bitmap.Config.ARGB_8888);

    // 各ピクセルを黒か白で埋める
    for (int y = 0; y < byteMatrix.getHeight(); ++y) {
        for (int x = 0; x < byteMatrix.getWidth(); ++x) {
            byte val = byteMatrix.get(x, y);
            bitmap.setPixel(x, y, val == 1 ? Color.BLACK : Color.WHITE);
        }
    }

    // 必要な大きさに拡大する
    bitmap = Bitmap.createScaledBitmap(bitmap, size, size, false);

    return bitmap;
}

補足

Encoder.encode()の第二引数はエラー訂正レベルです。ErrorCorrectionLevel.Hが最も高く、ErrorCorrectionLevel.Q,ErrorCorrectionLevel.M,ErrorCorrectionLevel.Lとなるにつれて低くなります。
エラー訂正レベルが高いほうが、汚れ等でコードの一部が見えなくなっても正しく読み取れるようになりますが、その分データ量(画像サイズ)が大きくなります。

bitmap.setPixel()の部分で実際の色を決めます。違う色にしたい場合はColor.REDなどに変更することも可能です。

23
25
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
23
25