>  기사  >  Java  >  Java에서 QR 코드 기능을 구현하기 위한 예제 코드

Java에서 QR 코드 기능을 구현하기 위한 예제 코드

黄舟
黄舟원래의
2017-03-09 10:57:291573검색

오늘 글은 주로 자바를 이용해 QR코드 기능을 구현한 글입니다. 필요한 친구들이 참고하면 좋을 것 같아요. , 그래서 유용하고 누구나 사용할 수 있는 몇 가지 기술 코드를 차례로 작성했습니다. 상호 학습과 의사소통을 촉진합니다.

오늘 글에서는 주로 Java를 사용하여 QR 코드를 구현합니다.

기능을 보다 빠르고 효과적으로 구현하기 위해 코드를 작성하기 전에 전반적인 아이디어에 대해 이야기해 보겠습니다.

(1) 먼저 QR 코드 기능을 구현하려면 com.google.zxing의 핵심 jar 패키지를 가져와야 합니다. 여기서 가져온 것은 core-3.2.1.jar입니다.

( 2) 소위 QR 코드는 필요한 내용을 사진에 넣는 것에 불과하므로 여기서는 먼저 매개변수 내용으로 사진을 만듭니다.

private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
hints.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,
hints);
int width = bitMatrix.getWidth();
int height = bitMatrix.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, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
// 插入图片
QRCodeUtil.insertImage(image, imgPath, needCompress);
return image;
}
//插入logo 如不需要logo可以执行此方法
private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {
File file = new File(imgPath);
if (!file.exists()) {
System.err.println("" + imgPath + "  该文件不存在!");
return;
}
Image src = ImageIO.read(new File(imgPath));
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) { // 压缩LOGO
if (width > WIDTH) {
width = WIDTH;
}
if (height > HEIGHT) {
height = HEIGHT;
}
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = tag.getGraphics();
g.drawImage(image, 0, 0, null); // 绘制缩小后的图
g.dispose();
src = image;
}
// 插入LOGO
Graphics2D graph = source.createGraphics();
int x = (QRCODE_SIZE - width) / 2;
int y = (QRCODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}

(3) 이제 QR 코드 이미지를 생성하는 방법이 작성되었습니다. 다음 단계는 이 방법을 호출하는 것입니다.

/**
* 生成二维码(内嵌LOGO)
* 
* @param content
*      内容
* @param imgPath
*      LOGO地址
* @param destPath
*      存放目录
* @param needCompress
*      是否压缩LOGO
* @throws Exception
*/
public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {
BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
mkdirs(destPath);
String file = new Random().nextInt(99999999) + ".jpg";
ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + file));
}
/**
* 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
* 
* @author LongJin
* @date 2013-12-11 上午10:16:36
* @param destPath
*      存放目录
*/
public static void mkdirs(String destPath) {
File file = new File(destPath);
// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}

(4) 로고를 원하지 않으면 호출 시 로고 경로를 null로 전달하면 됩니다.


(5) 이 시점에서 QR 코드 생성 도구가 완성되었습니다. 물론 누군가 QR 코드를 파싱해야 할 수도 있으므로 여기에도 QR 코드 파싱 방법을 적어 두겠습니다. 나중에 다시 확인해 보세요.


아아앙

위 내용은 Java에서 QR 코드 기능을 구현하기 위한 예제 코드의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

성명:
본 글의 내용은 네티즌들의 자발적인 기여로 작성되었으며, 저작권은 원저작자에게 있습니다. 본 사이트는 이에 상응하는 법적 책임을 지지 않습니다. 표절이나 침해가 의심되는 콘텐츠를 발견한 경우 admin@php.cn으로 문의하세요.