티스토리 뷰

반응형

[Android] 안드로이드 QRcode 적용하기 - zxing-android-embedded

QR코드 생성하기 / QR코드 읽기 / QRcode Reader / QRcode Writer 

QRCode의 Zxing 라이브러리를 안드로이드에서 더 쉽게 설정하고 사용할 수 있도록 만든 zxing-android-embedded 라이브러리를 이용하여 앱에 적용해보자.




  Gradle 설정

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
repositories {
    jcenter()
}

dependencies {
    ...
    compile 'com.android.support:appcompat-v7:25.3.1' // Version 23+ is Required
    compile 'com.journeyapps:zxing-android-embedded:3.5.0'
    ...
}

위와 같이 Gradle 설정을 해준다. 

안드로이드 빌드 툴 버전은 23.0.2 미만의 버전에서는 컴파일 에러가 발생한다고 한다. 


  QRCode Reader 호출하기

QRCode Reader를 호출하고 호출된 값을 찾는 작업만 하면 된다.


 1.  호출

1
new IntentIntegrator(this).initiateScan();


위와 같이 새로운 Activity가 실행되는 형태로 화면전환이 이루어진다.


 2.  호출된 값

위 화면에서 QRCode가 Detect되면 QRCode Reader는 종료되고 원래의 Activity로 돌아와 onActivityResult 를 호출하게 된다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
    protected void onActivityResult (int requestCode, int resultCode, Intent data) {
        //  com.google.zxing.integration.android.IntentIntegrator.REQUEST_CODE 
        //  = 0x0000c0de; // Only use bottom 16 bits
        if (requestCode == IntentIntegrator.REQUEST_CODE) {
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (result == null) {
                // 취소됨
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            } else {
                // 스캔된 QRCode --> result.getContents()
                Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }

result.getContents()의 값으로 이후에 QRCode 컨텐츠를 처리 하면 된다.


  QRCode Write 생성하기

QRCode, Barcode 등 다양한 형태의 이미지 코드의 이미지를 생성 할 수 있다.

아래의 BarcodeFormat을 참조하여 생성하고자 하는 Format을 지정하여 사용하면 된다.

 1.  BarcodeFormat

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
public enum BarcodeFormat {

  /** Aztec 2D barcode format. */
  AZTEC,

  /** CODABAR 1D format. */
  CODABAR,

  /** Code 39 1D format. */
  CODE_39,

  /** Code 93 1D format. */
  CODE_93,

  /** Code 128 1D format. */
  CODE_128,

  /** Data Matrix 2D barcode format. */
  DATA_MATRIX,

  /** EAN-8 1D format. */
  EAN_8,

  /** EAN-13 1D format. */
  EAN_13,

  /** ITF (Interleaved Two of Five) 1D format. */
  ITF,

  /** MaxiCode 2D barcode format. */
  MAXICODE,

  /** PDF417 format. */
  PDF_417,

  /** QR Code 2D barcode format. */
  QR_CODE,

  /** RSS 14 */
  RSS_14,

  /** RSS EXPANDED */
  RSS_EXPANDED,

  /** UPC-A 1D format. */
  UPC_A,

  /** UPC-E 1D format. */
  UPC_E,

  /** UPC/EAN extension format. Not a stand-alone format. */
  UPC_EAN_EXTENSION

}



 2.  생성하기

아래의 코드에 변환할 String만 입력해주면 된다.

encode의 파라미터는 (String 변환할 내용, BarcodeFormat 변환할 바코드포멧, int 넓이, int 높이)

순으로 작성하면 된다.

1
2
3
4
5
6
7
8
    public void generateRQCode(String contents) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        try {
            Bitmap bitmap = toBitmap(qrCodeWriter.encode(contents, BarcodeFormat.QR_CODE, 100, 100));
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }


 3.  encode 리턴형태인 BitMatrix를 Bitmap으로 변환하기

2번 생성하기에서 사용된 toBitmap 이다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
    public static Bitmap toBitmap(BitMatrix matrix) {
        int height = matrix.getHeight();
        int width = matrix.getWidth();
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                bmp.setPixel(x, y, matrix.get(x, y) ? Color.BLACK : Color.WHITE);
            }
        }
        return bmp;
    }





  예제 Activity 전체내용

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
package dwfox.zxingexample;

import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.integration.android.IntentIntegrator;
import com.google.zxing.integration.android.IntentResult;
import com.google.zxing.qrcode.QRCodeWriter;

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.btn_start_qrcode_reader).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startQRCode();
            }
        });
        findViewById(R.id.btn_start_qrcode_generate).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String content = ((EditText) findViewById(R.id.edt_qrcode_content)).getText().toString();
                if (content.isEmpty()) {
                    Toast.makeText(MainActivity.this, "문자를 입력해주세요", Toast.LENGTH_LONG).show();
                } else {
                    generateRQCode(content);
                }

            }
        });

    }

    public void startQRCode() {
        new IntentIntegrator(this).initiateScan();
    }

    public void generateRQCode(String contents) {
        QRCodeWriter qrCodeWriter = new QRCodeWriter();
        try {
            Bitmap bitmap = toBitmap(qrCodeWriter.encode(contents, BarcodeFormat.QR_CODE, 200, 200));
            ((ImageView) findViewById(R.id.iv_generated_qrcode)).setImageBitmap(bitmap);
        } catch (WriterException e) {
            e.printStackTrace();
        }
    }

    public static Bitmap toBitmap(BitMatrix matrix) {
        int height = matrix.getHeight();
        int width = matrix.getWidth();
        Bitmap bmp = Bitmap.createBitmap(width, height, Bitmap.Config.RGB_565);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                bmp.setPixel(x, y, matrix.get(x, y) ? Color.BLACK : Color.WHITE);
            }
        }
        return bmp;
    }


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (requestCode == IntentIntegrator.REQUEST_CODE) {
            IntentResult result = IntentIntegrator.parseActivityResult(requestCode, resultCode, data);
            if (result == null) {
                Toast.makeText(this, "Cancelled", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(this, "Scanned: " + result.getContents(), Toast.LENGTH_LONG).show();
            }
        } else {
            super.onActivityResult(requestCode, resultCode, data);
        }
    }
}


반응형
댓글
공지사항
최근에 올라온 글
최근에 달린 댓글
Total
Today
Yesterday
링크
«   2024/03   »
1 2
3 4 5 6 7 8 9
10 11 12 13 14 15 16
17 18 19 20 21 22 23
24 25 26 27 28 29 30
31
글 보관함