Spring BootでQRコードを生成してスキャンする方法

QRコード生成の基本設定

ZXingライブラリを使用してQRコードを生成するための依存関係を追加します。

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.2.1</version>
</dependency>

アプリケーション設定

application.ymlファイルにQRコード関連の設定を追加します。

server:
  port: 8080

qrCode:
  codeUrl: http://your-server-ip:8080/code/codeUrl/
  codePath: /path/to/qr/codes

QRコード生成ユーティリティ

QRコードを生成するための主要なメソッドを含むクラスです。

public class QRCodeGenerator {
    private static final int BLACK = 0xFF000000;
    private static final int WHITE = 0xFFFFFFFF;

    public static String generateQRCodeImage(String content, String path, String filename) {
        try {
            Map<EncodeHintType, String> hints = new HashMap<>();
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            
            BitMatrix matrix = new MultiFormatWriter().encode(
                content, 
                BarcodeFormat.QR_CODE, 
                400, 
                400, 
                hints
            );
            
            File outputFile = new File(path, filename);
            if (outputFile.exists() || 
                ((outputFile.getParentFile().exists() || 
                outputFile.getParentFile().mkdirs()) && 
                outputFile.createNewFile())) {
                
                writeQRImage(matrix, "jpg", outputFile);
                return outputFile.getAbsolutePath();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static void writeQRImage(BitMatrix matrix, String format, File file) 
        throws IOException {
        BufferedImage image = convertToImage(matrix);
        if (!ImageIO.write(image, format, file)) {
            throw new IOException("画像の保存に失敗しました: " + format);
        }
    }

    private static BufferedImage convertToImage(BitMatrix matrix) {
        int width = matrix.getWidth();
        int height = matrix.getHeight();
        BufferedImage image = new BufferedImage(
            width, 
            height, 
            BufferedImage.TYPE_INT_RGB
        );
        
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
            }
        }
        return image;
    }
}

APIエンドポイント

QRコード生成と処理のためのREST APIエンドポイントです。

@RestController
@RequestMapping("/api/qrcode")
public class QRCodeController {

    @Autowired
    private QRCodeConfig qrConfig;

    @GetMapping("/generate")
    public String generateQR(@RequestParam String data) {
        String url = qrConfig.getCodeUrl() + "?data=" + data;
        return QRCodeGenerator.generateQRCodeImage(
            url, 
            qrConfig.getCodePath(), 
            data + ".jpg"
        );
    }

    @GetMapping("/scan")
    public String handleScan(@RequestParam String data) {
        System.out.println("QRコードから読み取ったデータ: " + data);
        return "処理されたデータ: " + data;
    }
}

テスト方法

1. QRコード生成エンドポイントにアクセス:

http://your-server-ip:8080/api/qrcode/generate?data=test123

2. 生成されたQRコードをスマートフォンでスキャン

タグ: SpringBoot QRコード ZXing Java 画像処理

6月22日 20:10 投稿