51
64

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ZXingで、QRコードを撮れる

Last updated at Posted at 2015-07-23

ZXingとは

  • ZXing は Google が開発して公開している、様々な一次元や二次元のバーコードの生成/操作ができるオープンソースライブラリ
  • https://github.com/zxing/zxing

Androidプロジェクトに、ZXingライブラリを追加

app/build.gradle

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    ......
    compile 'com.journeyapps:zxing-android-embedded:3.0.1@aar'
    compile 'com.google.zxing:core:3.2.0'
}

zxing-android-embeddedとは

QRコードを取得するために、コード実装

AndroidManifest.xml

 <uses-permission android:name="android.permission.CAMERA"/>
 <uses-permission android:name="android.permission.FLASHLIGHT"/>

Activity実装

AndroidManifest.xml
 <activity
            android:name=".CaptureActivityAnyOrientation"
            android:screenOrientation="fullSensor"
            android:stateNotNeeded="true"
            android:theme="@style/zxing_CaptureTheme"
            android:windowSoftInputMode="stateAlwaysHidden" />
CaptureActivityAnyOrientation.java
import com.journeyapps.barcodescanner.CaptureActivity;

public class CaptureActivityAnyOrientation extends CaptureActivity {
}
MainActivity.java

        Button mBtnCamera = (Button) findViewById(R.id.camera_button);
        mBtnCamera.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                IntentIntegrator integrator = new IntentIntegrator(LoginActivity.this);            
                integrator.setCaptureActivity(CaptureActivityAnyOrientation.class);
                integrator.setOrientationLocked(false);
                integrator.initiateScan();
            }
        });
MainActivity.java
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        IntentResult scanResult = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
        if (scanResult != null) {
            TextView qResultView = (TextView) findViewById(R.id.qr_text_view);
            qResultView.setText(scanResult.getContents());
            Log.d("scan", "==-----:  " + scanResult.getContents());
        }
    }

QRコードを生成するために、コード実装

MainActivity.java
       Button mBtnCreateQRcode = (Button) findViewById(R.id.create_qrcode);
        mBtnCreateQRcode.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                createQRcode();
            }
        });

......

    private void createQRcode() {

        Bitmap qr = null;
        try {
            qr = createQRCodeByZxing("http://google.co.jp", 400);
        } catch (WriterException e) {
            Log.d("createQRcode", "error: ", e);
        }

        try {
            File root = Environment.getExternalStorageDirectory();

            // 日付でファイル名を作成 
            Date mDate = new Date();
            SimpleDateFormat fileName = new SimpleDateFormat("yyyyMMdd_HHmmss");

            // 保存処理開始
            FileOutputStream fos = null;
            fos = new FileOutputStream(new File(root, fileName.format(mDate) + ".jpg"));

            // jpegで保存
            qr.compress(Bitmap.CompressFormat.JPEG, 100, fos);

            // 保存処理終了
            fos.close();
        } catch (Exception e) {
            Log.e("Error", "" + e.toString());
        }
    }

    public Bitmap createQRCodeByZxing(String contents,int size) throws WriterException {
        //QRコードをエンコードするクラス
        QRCodeWriter writer = new QRCodeWriter();

        //異なる型の値を入れるためgenericは使えない
        Hashtable encodeHint = new Hashtable();

        //日本語を扱うためにシフトJISを指定
        encodeHint.put(EncodeHintType.CHARACTER_SET, "shiftjis");

        //エラー修復レベルを指定
        //L 7%が復元可能
        //M 15%が復元可能
        //Q 25%が復元可能
        //H 30%が復元可能
        encodeHint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);

        BitMatrix qrCodeData = writer.encode(contents, BarcodeFormat.QR_CODE, size, size, encodeHint);

        //QRコードのbitmap画像を作成
        Bitmap bitmap = Bitmap.createBitmap(size, size, Bitmap.Config.ARGB_8888);
        bitmap.eraseColor(Color.argb(255, 255, 255, 255)); //いらないかも
        for (int x = 0; x < qrCodeData.getWidth(); x++) {
            for (int y = 0; y < qrCodeData.getHeight(); y++) {
                if (qrCodeData.get(x, y) == true) {
                    //0はBlack
                    bitmap.setPixel(x, y, Color.argb(255, 0, 0, 0));
                } else {
                    //-1はWhite
                    bitmap.setPixel(x, y, Color.argb(255, 255, 255, 255));
                }
            }
        }

        return bitmap;
    }
51
64
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
51
64

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?