前言
时间过得真快,都已经两个月多没有写博文了,由于最近换了一份工作,有点忙所以就一直没有写文章,非常抱歉。
正文
ZXing是一个开放源码的,用Java实现的多种格式的1D/2D条码图像处理库,它包含了联系到其他语言的端口。Zxing可以实现使用手机的内置的摄像头完成条形码的扫描及解码。
首先,我们要新建一个web工程(使用maven构建),然后在pom.xml里面添加zxing依赖
1 2 3 4 5 | <dependency> <groupId>com.google.zxing</groupId> <artifactId>javase</artifactId> <version>3.2.1</version> </dependency> |
然后在其控制层生成图像,因为Demo演示我也就没有分层来写
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 | 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
Github:https://github.com/Licoy/qrcode-google-zxing
后记
本文仅供参考,具体细节未写出,有任何纰漏可以下方评论区指出,谢谢。( 说实话,我自己都看不下去了)
2017年12月12日 下午10:08 11楼
学习啦。谢谢。
2017年12月06日 下午3:58 12楼
一直在找这个,今天就遇见了,不错。就和你需要酒,我就给你送酒一样!
2017年12月06日 下午9:25 1层
@商品免费领取 你有酒,我有歌。
2017年08月28日 下午10:56 13楼
2017年08月29日 下午4:23 1层
@微先生
2017年08月21日 上午7:26 14楼
2017年08月21日 上午9:25 1层
@轩陌 thank you
2017年08月15日 上午8:20 15楼
又有新的方案了,赞!
2017年08月15日 下午4:43 1层
@Koolight
2017年08月11日 下午9:24 16楼
我觉得java好难的。。
2017年08月12日 上午7:48 1层
@晴和君 难也不难,简单也不简单
2017年08月09日 下午2:46 17楼
朋友 交换链接吗
2017年08月09日 下午2:48 1层
@bandwagonhost 非常抱歉,贵站与本站友链对象不符,暂不给予友链,谢谢您的支持!
2017年08月01日 下午2:39 18楼
看习惯了PHP,再看这些JAVA代码,很陌生的感觉
2017年08月01日 下午2:40 1层
@boke112导航 语法不一样,是有点陌生