Develop/JAVA

[JAVA] QR코드 생성 후 서버에 이미지로 저장

issuemaker99 2024. 8. 30. 10:03
728x90

QR코드를 바이트형태로 바로 보여줄 수도 있지만 이미지 형태로 저장해야 하는 경우도 있다.

 

▶ Gradle 라이브러리 추가

// QR Code - zxing
implementation group: 'com.google.zxing', name: 'javase', version: '3.5.0'
implementation group: 'com.google.zxing', name: 'core', version: '3.5.0'

 

▶ 경로와 파일명은 상황에 맞춰 조정하시면 됩니다. 이미 파일이 존재하는지 체크해서 파일이 있으면 생성하지 않고 파일이 없으면 QR코드 이미지를 생성 합니다.

@PostMapping("/edu200/edu200110/clcrQrMake")
public ModelAndView getCrClQrCodeMake(HttpServletRequest request, @RequestBody TrnDto vo) {
    ModelAndView mav = new ModelAndView(CmConstant.JSON_VIEW);

    String fileName = vo.getAnpTrnNo() + "_" + vo.getCrclEs();
    String savePath = "src/main/resources/static/images/clcrQr/"+ vo.getAnpTrnNo() +"/"+ fileName +".png";
    File file = new File(savePath);

    //파일 경로가 없으면 파일 생성
    if (!file.exists()) {
        file.mkdirs();

        String content = "https://issuemaker99.tistory.com";

        try {
            //QR 생성
            QRCodeWriter qrCodeWriter = new QRCodeWriter();
            BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, 500, 500);
            BufferedImage bufferedImage = MatrixToImageWriter.toBufferedImage(bitMatrix);

            //파일 생성
            File temp = new File(savePath);

            //ImageIO를 사용하여 파일쓰기
            ImageIO.write(bufferedImage, "png", temp);
        } catch (IOException | WriterException e) {
            e.printStackTrace();
            return makeJsonResult(mav, CmStatus.JSON_ERROR, "");
        }
        return makeJsonResult(mav, CmStatus.JSON_SUCC, fileName + ".png");
    }else {
        return makeJsonResult(mav, CmStatus.JSON_SUCC, fileName + ".png");
    }        
}
LIST