QR 코드 생성을 위한 안드로이드 구현 방법
안드로이드 앱에서 QR 코드를 생성하는 기능은 일반적으로 오픈소스 라이브러리 ZXing를 활용한다. 이 라이브러리는 다차원 바코드 처리를 위한 표준 도구로, 특히 QR 코드 생성 및 인식에 널리 사용된다.
1. 의존성 추가
Android Studio 환경에서는 build.gradle 파일에 다음 의존성을 추가하면 된다:
dependencies {
implementation 'com.google.zxing:core:3.3.0'
}
이렇게 하면 필요한 핵심 클래스가 프로젝트에 포함된다.
2. 기본 생성 메서드 구현
다음은 문자열을 입력받아 비트맵 이미지를 반환하는 유틸리티 클래스 예시이다. 이 클래스는 다양한 설정 옵션을 지원하며, 한글 등 특수 문자도 정상 처리 가능하다.
public class QrCodeGenerator {
public static Bitmap generate(String content, int width, int height) {
return generate(content, width, height, "UTF-8", "H", "2", Color.BLACK, Color.WHITE);
}
public static Bitmap generate(
String content,
int width,
int height,
String charset,
String errorLevel,
String margin,
int darkColor,
int lightColor
) {
if (content == null || content.isEmpty() || width <= 0 || height <= 0) {
return null;
}
try {
Map<EncodeHintType, Object> hints = new EnumMap<>(EncodeHintType.class);
if (charset != null && !charset.isEmpty()) {
hints.put(EncodeHintType.CHARACTER_SET, charset);
}
if (errorLevel != null && !errorLevel.isEmpty()) {
hints.put(EncodeHintType.ERROR_CORRECTION, errorLevel);
}
if (margin != null && !margin.isEmpty()) {
hints.put(EncodeHintType.MARGIN, Integer.parseInt(margin));
}
BitMatrix matrix = 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] = matrix.get(x, y) ? darkColor : lightColor;
}
}
Bitmap bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888);
bitmap.setPixels(pixels, 0, width, 0, 0, width, height);
return bitmap;
} catch (WriterException e) {
e.printStackTrace();
}
return null;
}
}
3. 사용 예시
메인 액티비티에서 이미지뷰에 생성된 QR 코드를 표시할 수 있다:
ImageView qrImage = findViewById(R.id.qr_image);
Bitmap qrBitmap = QrCodeGenerator.generate("https://example.com", 400, 400);
qrImage.setImageBitmap(qrBitmap);
4. 주요 설정 파라미터 설명
-
문자 인코딩 (
charset): 기본값은ISO-8859-1이며, 한글이나 특수문자를 포함한 경우 반드시"UTF-8"을 사용해야 한다. 그렇지 않으면 디코딩 실패 발생. -
오류 복구 수준 (
errorLevel):L,M,Q,H중 선택 가능. 값이 클수록 오류에 강건하지만, 데이터 용량이 감소하고 크기가 커진다.H는 최고 수준의 회복 능력을 제공한다. -
여백(
margin): QR 코드 외곽에 추가되는 흰색 여백의 크기. 기본값은4이며,0으로 설정하면 경계가 없어져 일부 스캐너에서 인식이 어려울 수 있다. -
색상(
darkColor,lightColor): 검정/하얀색 외에도 다른 색상을 지정할 수 있지만, 대부분의 스캐너는 전통적인 검백 조합을 기준으로 작동하므로 권장되지 않는다.
5. 내부 동작 원리
QRCodeWriter.encode() 메서드는 입력된 문자열을 기반으로 비트 매트릭스를 계산한다. 이 매트릭스는 각 픽셀이 검정인지 흰색인지 결정하는 이진 정보를 담고 있으며, 이후 이를 직접 픽셀 배열로 변환하여 Bitmap 객체를 생성한다.
6. 성능 최적화 팁
원래 ZXing 라이브러리는 약 541KB로, 많은 기능이 포함되어 있지만, 실제 필요한 것은 단지 QRCodeWriter와 관련 클래스뿐이다.
실제 프로젝트에서는 불필요한 클래스를 제거하고, 필요한 23개 클래스만 추출하여 사이즈를 130KB까지 줄일 수 있었다. 이 과정에서 주석 제거도 고려되었지만, 유지보수 측면에서 보류하였다.