ホームページ  >  記事  >  Java  >  Java が Google zxing に基づいて QR コードを生成およびデコードする方法の例

Java が Google zxing に基づいて QR コードを生成およびデコードする方法の例

黄舟
黄舟オリジナル
2017-07-26 15:22:231430ブラウズ

この記事では、主に Google zxing に基づく Java QR コードの生成とデコードについて詳しく紹介します。興味のある方は参考にしてください。この記事では、Java QR コードの生成を皆さんと共有します。具体的な内容は以下のとおりです


1. Maven の依存関係を追加します (デコード時に QR コード画像をアップロードする必要があるため、ファイル アップロード パッケージに依存する必要があります)


<!-- google二维码工具 -->
<dependency>
 <groupId>com.google.zxing</groupId>
 <artifactId>javase</artifactId>
 <version>3.1.0</version>
</dependency>

<!-- 文件上传 -->
<dependency>
 <groupId>commons-fileupload</groupId>
 <artifactId>commons-fileupload</artifactId>
 <version>1.3.1</version>
</dependency>
<dependency>
 <groupId>commons-io</groupId>
 <artifactId>commons-io</artifactId>
 <version>2.4</version>
</dependency>

2. 作成2 つの QR コード インターフェイスを生成します (インターフェイス パラメーターは QR コードのコンテンツ、通常は URL)

/**
 * 生成二维码
 * google zxing 实现
 * @param text
 * @return
 */
@RequestMapping(value = "/qrcode/encode", method = RequestMethod.POST)
public void encodeQrCode(String text, HttpServletResponse response) {
  try {
   // 设置二维码参数
   Map<EncodeHintType, Object> hints = new HashMap<EncodeHintType, Object>();
   hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
   BitMatrix bitMatrix = new MultiFormatWriter().encode(text, BarcodeFormat.QR_CODE, 150, 150, hints);
   //返回二维码
   MatrixToImageWriter.writeToStream(bitMatrix, "jpg", response.getOutputStream());
  } catch (Exception e) {
   e.printStackTrace();
  }
}

3. QR コード デコード インターフェイスを作成します (デコードされた QR コード コンテンツを直接返します)

/**
 * 二维码图片解码
 * google zxing 实现
 * @param qrImg
 * @return
 */
@RequestMapping(value = "/qrcode/decode", method = RequestMethod.POST)
public String decodeQrCode(MultipartFile qrImg) {
  if (!qrImg.isEmpty()) {
   try {
     BufferedImage image = ImageIO.read(qrImg.getInputStream());

     BinaryBitmap binaryBitmap = new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(image)));

     // 定义二维码的参数:
     HashMap<DecodeHintType, Object> hints = new HashMap<>();
     // 定义字符集
     hints.put(DecodeHintType.CHARACTER_SET, "utf-8");

     Result result = new MultiFormatReader().decode(binaryBitmap, hints);

     return result.getText();
   } catch (Exception e) {
     e.printStackTrace();
   }
  }

  return null;
}

以上がJava が Google zxing に基づいて QR コードを生成およびデコードする方法の例の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。