java生成解析二维码

说明

本文介绍使用zxing来生成和解析二维码。

maven坐标如下:

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.0</version>
</dependency>

1 zxing生成二维码示例

/**
 * 生成二维码并写到指定的输出流
 * 
 * @param width
 *            二维码宽度
 * @param height
 *            二维码高度
 * @param content
 *            二维码内容
 * @param dest
 *            输出目标,可以是
 *            {@link FileOutputStream}、{@link ServletOutputStream}等任何输出流
 * @throws IOException
 * @throws WriterException
 */
public void generateQRCode(int width, int height, String content, OutputStream dest)
  throws IOException, WriterException {

  Map<EncodeHintType, Object> map = new HashMap<>();
  // 编码方式
  map.put(EncodeHintType.CHARACTER_SET, "utf-8");
  // 纠错级别--中级
  map.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);
  // 内边距
  map.put(EncodeHintType.MARGIN, 2);

  // 生成二维码
  BitMatrix matrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, map);
  // 写入到任何输出流皆可
  MatrixToImageWriter.writeToStream(matrix, "png", dest);
}

2 zxing解析二维码示例

/**
 * 从输入流解析二维码
 * 
 * @param inputStream
 * @return
 * @throws IOException
 * @throws NotFoundException
 */
@SuppressWarnings("unchecked")
public Result parseQRCode(InputStream inputStream) throws IOException, NotFoundException {
  @SuppressWarnings("rawtypes")
  Map map = new HashMap();

  map.put(EncodeHintType.CHARACTER_SET, "utf-8");

  BinaryBitmap binaryBitmap = null;

  BufferedImage bufferedImage = ImageIO.read(inputStream);

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

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

  return result;
}

3 一个基于zxing第三方开源项目

地址:https://github.com/kenglxn/QRGen

使用示例:

QRCode.from("https://github.com/kenglxn/QRGen")//
  .withSize(400, 400)//
  .withHint(EncodeHintType.CHARACTER_SET, "UTF-8")//
  .withErrorCorrection(ErrorCorrectionLevel.M)//
  .withHint(EncodeHintType.MARGIN, 2)//
  .writeTo(new FileOutputStream(new File("/Users/hylexus/tmp/t.png")));

代码地址

https://github.com/hylexus/blog-src/tree/master/qr-code

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值