본문 바로가기

JAVA개발

[JAVA개발] zxing라이브러리를 이용하여 QR코드생성

1. pom.xml dependency  추가하기

<!-- QR code -->
  <dependency>
   <groupId>com.google.zxing</groupId>
   <artifactId>javase</artifactId>
   <version>3.1.0</version>
  </dependency>

 

2. QR코드 등록을 위한 클래스 생성

QR코드 등록을 위해 별도의 QRUtil 이라는 클래스와 makeQR이라는 메서드를 생성하였습니다.

@param url : QR에 작성할 URL

@param width : QR 이미지 가로사이즈

@param height : QR 이미지 세로사이즈

@param file_path : 생성할 파일의 디렉토리 경로

@param file_name : 생성할 파일의 파일명

public class QRUtil {
 
 public static void makeQR(String url , int width , int height , String file_path , String file_name){
  try{
   File file = null;
   
   file = new File(file_path);
   if(!file.exists()){
    file.mkdirs();
   }
   QRCodeWriter writer = new QRCodeWriter();
   url = new String(url.getBytes("UTF-8") , "ISO-8859-1");
   BitMatrix matrix = writer.encode(url, BarcodeFormat.QR_CODE, width, height);
   //QR코드 색상
   int qrColor = 0xFFad1004;
   MatrixToImageConfig config = new MatrixToImageConfig(qrColor , 0xFFFFFFFF);
   BufferedImage qrImage = MatrixToImageWriter.toBufferedImage(matrix , config);
    ImageIO.write(qrImage ,  "png" ,  new File(file_path+file_name));
  } catch (Exception e) {
   e.printStackTrace();
  }  
 }
}

3. 테스트를 하기위한 Controller에 소스작성

@RequestMapping("/codetest")
 public void codetest() throws WriterException , IOException{
  String url = "http://sgroom.tistory.com";
  int width = 150;
  int height = 150;
  
  String file_path = "G:"+File.separator+"qr"+File.separator;
  String file_name = "test.png";
  QRUtil.makeQR(url , width , height , file_path , file_name);
  
 } 

실행시 return 값이 없어 페이지상으로는 404에러가 발생합니다. 

확인할부분은 소스상 지정된 경로에 정상적으로 파일생성이 완료 되었는지 확인하는 부분입니다.

String file_path 에서 작성한 경로 G드라이브에 qr폴더안에 test.png파일이 생성되었는지 확인해 봅니다. 

정상적으로 해당 경로에 파일이 생성된것을 확인하였습니다.

QR코드의 색상을 다양하게 생성할수 있습니다.

http://encycolorpedia.kr/

해당 사이트로 이동합니다.

 검색창을 클릭하여 원하는 색상을 클릭하시거나, 일반 웹에서 사용되는 RGB생상코드 또는 white와 같은

문자열 검색도 가능합니다.

자신이 원하는 생상의 코드를 모르실경우 ColorCop 를 구글에서 검색하여 사용하는것도 좋은 방법인것

같습니다. 무료 다운로드가 가능하며 스포이드 모양을 클릭하여하여 원하시는 색상으로 이동해 클릭을 빼면 코드가

우측에 자동으로 나오며 해당 코드를 검색해 원하시는 색상을 바로 찾으실수 있습니다. 

코드를 검색후 나오는 내용에서 해당 코드를 기재하여 실행시 해당 코드 색상으로 QR코드가 생성됩니다.

 해당 코드는 0xfff9dce0 입니다.

감사합니다^^