前言
时间过得真快,都已经两个月多没有写博文了,由于最近换了一份工作,有点忙所以就一直没有写文章,非常抱歉。
正文
ZXing是一个开放源码的,用Java实现的多种格式的1D/2D条码图像处理库,它包含了联系到其他语言的端口。Zxing可以实现使用手机的内置的摄像头完成条形码的扫描及解码。
首先,我们要新建一个web工程(使用maven构建),然后在pom.xml里面添加zxing依赖
<dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.2.1</version> </dependency>
然后在其控制层生成图像,因为Demo演示我也就没有分层来写
package cn.licoy.controller; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.MultiFormatWriter; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; import org.springframework.stereotype.Controller; import org.springframework.web.bind.annotation.GetMapping; import org.springframework.web.bind.annotation.RequestParam; import javax.servlet.ServletOutputStream; import javax.servlet.http.HttpServletResponse; import java.util.HashMap; import java.util.Map; /** * @author Licoy.cn * @version 1.0 / qrcode */ @Controller public class QrController { @GetMapping("/") public void get(@RequestParam(name = "w",defaultValue = "200",required = false) int width, @RequestParam(name = "h",defaultValue = "200",required = false) int height, @RequestParam(name = "f",defaultValue = "png",required = false) String format, @RequestParam(name = "c",defaultValue = "content") String content, HttpServletResponse response) throws Exception { ServletOutputStream out = response.getOutputStream(); Map<EncodeHintType,Object> config = new HashMap<>(); config.put(EncodeHintType.CHARACTER_SET,"UTF-8"); config.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); config.put(EncodeHintType.MARGIN, 0); BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,width,height,config); MatrixToImageWriter.writeToStream(bitMatrix,format,out); System.out.println("二维码生成完毕,已经输出到页面中。"); } }
最后启动该web启动,访问该web程序根目录即可显示二维码图片。
演示程序已经打包上传到Github,项目使用的是SpringBoot构建的,可以clone至本地然后使用idea打开运行即可。
Github:https://github.com/Licoy/qrcode-google-zxing
后记
本文仅供参考,具体细节未写出,有任何纰漏可以下方评论区指出,谢谢。( 说实话,我自己都看不下去了)
学习啦。谢谢。