스프링연동하기/spring3 기타설정

zxing 라이브러리를 이용하여 QR코드/큐알코드/바코드 이미지를 색상별로 생성해보도록 하자

개발로짜 2014. 8. 29. 15:01

요즘 모바일이 활성화되면서 사용되는 출력물 중 하나라고 생각되어서 포스팅 하게 되었다.

zxing 라이브러리를 이용하여 QR코드/큐알코드/바코드 이미지를 생성하고자 한다.


이번포스팅은 무척 심플하다 


1. pom.xml dependency 추가를 해주도록 하자


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

2. QR코드 유틸제작


유틸이라고 하기엔 그렇고 그냥 만들어보았음


클래스명을 QRUtil라고 주고 생성메서드를 makeQR이라고 만들어봄


import java.awt.image.BufferedImage;
import java.io.File;

import javax.imageio.ImageIO;

import com.google.zxing.BarcodeFormat;
import com.google.zxing.client.j2se.MatrixToImageConfig;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;

public class QRUtil {
	/**
	 * QR코드 유틸
	 * @param url : QR에 작성할 URL이다 
	 * @param width : QR 이미지 가로사이즈
	 * @param height : QR 이미지 세로사이즈
	 * @param file_path : 생성할파일의 디렉토리경로
	 * @param file_name : 생성할 파일의 파일명
	 */
	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	=	0xFF2e4e96;
	        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. QR 생성테스트를 위한 임의의 컨트롤러 호출 


꼭 컨트롤러가 아니여도 상관없다 핵심은 QRUtil에 들어있는 makeQR이 핵심



@RequestMapping(value="/makeqr")
public void makeqr() throws WriterException, IOException {
		String url = "http://roqkffhwk.tistory.com";
		int width = 50;
		int height = 50;
		
		String file_path = "D:"+File.separator+"qr"+File.separator;
		String file_name = "myblog.png";
		QRUtil.makeQR(url, width, height, file_path, file_name);
}

실행결과 브라우저에는 오류페이지만 뜨겠고, 우리가 여기서 확인해야 할 부분은

지정한 디렉토리 + 파일로 정상적으로 QR코드가 생성되었는지가 핵심이다.


※ 참고로 본인은 int qrColor 변수의 값을 변경하면서 다양한 색상으로 생성을 해보았다.



 색상코드값

결과화면 

 0xFF2d64e9

 


 0xFF2e4e96

 


 0xFF106f63

 


 0xFF766c15

 


 0xFF004555

 


 0xFF557615

 


 0xFF764515

 


 0xFFad1004

 


 0xFFbd4700

 




위와같이 다양한 색깔로 잘 나왔다.  잘 사용하시길 ^^







1. 지속적인 구독을 원하신다면 네이버 이웃추가 부탁드립니다


2. 도움이 되셨다면 공감한번 꾹! 눌러주세요

 

3. 궁금하신점이 있으시다면 댓글 GOGO 


Bye