当前位置:   article > 正文

zxing 生成 Qrcode (二维码)_zxing qrcode

zxing qrcode

Zxing生成Qrcode 工具类

1、引入依赖

  1. <dependency>
  2. <groupId>com.google.zxing</groupId>
  3. <artifactId>core</artifactId>
  4. <version>${zxing.version}</version>
  5. </dependency>
<zxing.version>3.4.0</zxing.version>

2、QrCodeUtils.java 

  1. import com.google.zxing.*;
  2. import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
  3. import com.google.zxing.common.*;
  4. import com.google.zxing.qrcode.QRCodeReader;
  5. import com.google.zxing.qrcode.QRCodeWriter;
  6. import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
  7. import com.insectcontrol.common.FileType;
  8. import javax.imageio.ImageIO;
  9. import java.awt.*;
  10. import java.awt.geom.RoundRectangle2D;
  11. import java.awt.image.BufferedImage;
  12. import java.io.*;
  13. import java.net.HttpURLConnection;
  14. import java.net.MalformedURLException;
  15. import java.net.URL;
  16. import java.util.Hashtable;
  17. import java.util.Map;
  18. import java.util.Objects;
  19. /**
  20. * 使用ZXing操作二维码(二维码生成和读的工具类), 二维码图片默认PNG格式
  21. * @author
  22. * @date 2019/06/07
  23. */
  24. public class QrCodeUtils {
  25. /**
  26. * 文本编码格式:UTF-8
  27. */
  28. public static final String CHARSET_DEF = "UTF-8";
  29. /**
  30. * 图案颜色:黑色
  31. */
  32. public static final int BLACK = 0xFF000000;
  33. /**
  34. * 背景色:白色
  35. */
  36. public static final int WHITE = 0xFFFFFFFF;
  37. /**
  38. * 图片最大值:1024
  39. */
  40. public static final int MAX_SIZE = 1024;
  41. /**
  42. * 图片最小值:400
  43. */
  44. public static final int MIN_SIZE = 400;
  45. /**
  46. * 编码提示配置
  47. */
  48. public static final Map<EncodeHintType, Object> HINTS = new Hashtable<EncodeHintType, Object>() {
  49. private static final long serialVersionUID = 1L;
  50. {
  51. // 指定纠错等级,纠错级别(L 7%、M 15%、Q 25%、H 30%)
  52. put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
  53. // 内容所使用字符集编码
  54. put(EncodeHintType.CHARACTER_SET, CHARSET_DEF);
  55. // put(EncodeHintType.MAX_SIZE, MAX_SIZE);//设置图片的最大值
  56. // put(EncodeHintType.MIN_SIZE, MIN_SIZE);//设置图片的最小值
  57. put(EncodeHintType.MARGIN, 0);//设置二维码边的空度,非负数
  58. }};
  59. /**
  60. * 解码配置
  61. */
  62. public static final Map<DecodeHintType, Object> DECODER_HINTS = new Hashtable<DecodeHintType, Object>() {
  63. private static final long serialVersionUID = 11L;
  64. {
  65. put(DecodeHintType.CHARACTER_SET, CHARSET_DEF); // 防止中文乱码
  66. }
  67. };
  68. /**
  69. * 生成包含字符串信息的二维码图片
  70. * @param outputStream 输出流
  71. * @param content 内容
  72. * @param qrCodeSize 二维码尺寸
  73. * @param imageFormat 图片格式(默认PNG格式)
  74. * @return
  75. * @throws
  76. */
  77. public static boolean createQrCode(OutputStream outputStream, String content, int qrCodeSize, String imageFormat)
  78. throws WriterException, IOException {
  79. content = new String(content.getBytes(CHARSET_DEF), "ISO-8859-1");
  80. Hashtable<EncodeHintType, ErrorCorrectionLevel> hintMap = new Hashtable<>();
  81. hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
  82. QRCodeWriter qrCodeWriter = new QRCodeWriter();
  83. //创建比特矩阵(位矩阵)的QR码编码的字符串
  84. BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
  85. // 使BufferedImage勾画QRCode (matrixWidth 是行二维码像素点)
  86. int matrixWidth = byteMatrix.getWidth();
  87. BufferedImage image = new BufferedImage(matrixWidth-200, matrixWidth-200, BufferedImage.TYPE_INT_RGB);
  88. image.createGraphics();
  89. Graphics2D graphics = (Graphics2D)image.getGraphics();
  90. graphics.setColor(Color.WHITE);
  91. graphics.fillRect(0, 0, matrixWidth, matrixWidth);
  92. // 使用比特矩阵画并保存图像
  93. graphics.setColor(Color.BLACK);
  94. for(int i = 0; i < matrixWidth; i++) {
  95. for(int j = 0; j < matrixWidth; j++) {
  96. if(byteMatrix.get(i , j)) {
  97. graphics.fillRect(i-100, j-100, 1, 1);
  98. }
  99. }
  100. }
  101. return ImageIO.write(image, StringUtil.trim(imageFormat, FileType.PNG.getSuffix()), outputStream);
  102. }
  103. /**
  104. * 生成包含字符串信息的二维码图片
  105. * @param fileFullPath 文件完整路径
  106. * @param content 内容
  107. * @param qrCodeSize 二维码尺寸
  108. * @param imageFormat 图片格式
  109. * @return
  110. * @throws WriterException
  111. * @throws IOException
  112. */
  113. public static boolean createQrCode(String fileFullPath, String content, int qrCodeSize, String imageFormat)
  114. throws WriterException, IOException {
  115. return createQrCode(new File(fileFullPath), content, qrCodeSize, imageFormat);
  116. }
  117. /**
  118. * 生成包含字符串信息的二维码图片
  119. * @param file 文件
  120. * @param content 内容
  121. * @param qrCodeSize 二维码尺寸
  122. * @param imageFormat 图片格式
  123. * @return
  124. * @throws WriterException
  125. * @throws IOException
  126. */
  127. public static boolean createQrCode(File file, String content, int qrCodeSize, String imageFormat)
  128. throws WriterException, IOException {
  129. return createQrCode(new FileOutputStream(file), content, qrCodeSize, imageFormat);
  130. }
  131. /**
  132. * 生成带Logo的条形码
  133. * @param qrCodeSrc 条形码文件
  134. * @param logoSrc Logo文件
  135. * @param content 内容
  136. * @param qrCodeWidth 条形码宽度
  137. * @param qrCodeHeight 条形码高度
  138. * @param imageFormat 条形码文件格式(默认PNG格式)
  139. * @return
  140. */
  141. public static boolean createQrCodeAndLogo(File qrCodeSrc, File logoSrc, String content, int qrCodeWidth,
  142. int qrCodeHeight, String imageFormat)
  143. throws WriterException, IOException {
  144. MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
  145. BufferedImage image = new BufferedImage(qrCodeWidth, qrCodeHeight, BufferedImage.TYPE_INT_RGB);
  146. // 开始利用二维码数据创建Bitmap图片,分别设为黑(0xFFFFFFFF)白(0xFF000000)两色
  147. BitMatrix matrix = multiFormatWriter.encode(content,//要编码的内容
  148. //编码类型,目前zxing支持:Aztec 2D,CODABAR 1D format,Code 39 1D,Code 93 1D ,Code 128 1D,
  149. //Data Matrix 2D , EAN-8 1D,EAN-13 1D,ITF (Interleaved Two of Five) 1D,
  150. //MaxiCode 2D barcode,PDF417,QR Code 2D,RSS 14,RSS EXPANDED,UPC-A 1D,UPC-E 1D,UPC/EAN extension,UPC_EAN_EXTENSION
  151. BarcodeFormat.QR_CODE,
  152. qrCodeWidth, //条形码的宽度
  153. qrCodeHeight, //条形码的高度
  154. HINTS);//生成条形码时的一些配置,此项可选
  155. for (int x = 0; x < qrCodeWidth; x++) {
  156. for (int y = 0; y < qrCodeHeight; y++) {
  157. image.setRGB(x, y, (matrix.get(x, y) ? BLACK : WHITE));
  158. }
  159. }
  160. int width = image.getWidth();
  161. int height = image.getHeight();
  162. if (Objects.nonNull(logoSrc) && logoSrc.exists()) {
  163. // 构建绘图对象
  164. Graphics2D g = image.createGraphics();
  165. // 读取Logo图片
  166. BufferedImage logo = ImageIO.read(logoSrc);
  167. // 开始绘制logo图片
  168. g.drawImage(logo, width * 2 / 5, height * 2 / 5, width * 2 / 10, height * 2 / 10, null);
  169. BasicStroke stroke = new BasicStroke(5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
  170. g.setStroke(stroke);// 设置笔画对象
  171. //指定弧度的圆角矩形
  172. RoundRectangle2D.Float round = new RoundRectangle2D.Float(width/5*2, height/5*2, width/5, height/5,20,20);
  173. g.setColor(Color.WHITE);
  174. g.draw(round);// 绘制圆弧矩形
  175. //设置logo 有一道灰色边框
  176. BasicStroke stroke2 = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
  177. g.setStroke(stroke2);// 设置笔画对象
  178. RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(width/5*2+2, height/5*2+2, width/5-4, height/5-4,20,20);
  179. g.setColor(new Color(128,128,128));
  180. g.draw(round2);// 绘制圆弧矩形
  181. g.dispose();
  182. logo.flush();
  183. }
  184. image.flush();
  185. return ImageIO.write(image, StringUtil.trim(imageFormat, FileType.PNG.getSuffix()), qrCodeSrc);
  186. }
  187. /**
  188. * 生成带Logo的条形码
  189. * @param qrCodeSrc 条形码文件路径
  190. * @param logoSrc Logo文件路径
  191. * @param content 内容
  192. * @param qrCodeWidth 条形码宽度
  193. * @param qrCodeHeight 条形码高度
  194. * @param imageFormat 条形码文件格式
  195. * @return
  196. * @throws WriterException
  197. * @throws IOException
  198. */
  199. public static boolean createQrCodeAndLogo(String qrCodeSrc, String logoSrc, String content, int qrCodeWidth,
  200. int qrCodeHeight, String imageFormat)
  201. throws WriterException, IOException {
  202. return createQrCodeAndLogo(new File(qrCodeSrc), new File(logoSrc), content, qrCodeWidth, qrCodeHeight, imageFormat);
  203. }
  204. /**
  205. * 读二维码并输出携带的信息
  206. * @param inputStream 输入流
  207. * @return
  208. * @throws IOException
  209. * @throws ReaderException
  210. */
  211. public static Result readQrCode(InputStream inputStream) throws IOException, ReaderException {
  212. //从输入流中获取字符串信息
  213. BufferedImage image = ImageIO.read(inputStream);
  214. //将图像转换为二进制位图源
  215. LuminanceSource source = new BufferedImageLuminanceSource(image);
  216. BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
  217. /*//解码设置编码方式为:utf-8
  218. Map<DecodeHintType, String> hints = new Hashtable<>();
  219. hints.put(DecodeHintType.CHARACTER_SET, CharacterSetECI.UTF8.name()); // 防止中文乱码*/
  220. QRCodeReader reader = new QRCodeReader();
  221. return reader.decode(bitmap, DECODER_HINTS);
  222. }
  223. /**
  224. * 根据url对象进行读取二维码
  225. * @param url URL对象
  226. * @return
  227. * @throws MalformedURLException
  228. * @throws IOException
  229. * @throws ReaderException
  230. */
  231. public static Result readQrCode(URL url) throws MalformedURLException, IOException, ReaderException {
  232. HttpURLConnection conn = (HttpURLConnection) url.openConnection();
  233. conn.setDoInput(true);
  234. conn.connect();
  235. InputStream is = conn.getInputStream();
  236. return readQrCode(is);
  237. }
  238. /**
  239. * 根据二维码图片路径读取
  240. * @param url 图片路径
  241. * @return
  242. * @throws MalformedURLException
  243. * @throws IOException
  244. * @throws ReaderException
  245. */
  246. public static Result readQrCodeByUrl(String url) throws MalformedURLException, IOException, ReaderException {
  247. return readQrCode(new URL(url));
  248. }
  249. /**
  250. * 读二维码并输出携带的信息
  251. * @param fileFullPath 文件完整路径
  252. * @return
  253. * @throws IOException
  254. * @throws ReaderException
  255. */
  256. public static Result readQrCode(String fileFullPath) throws IOException, ReaderException {
  257. return readQrCode(new File(fileFullPath));
  258. }
  259. /**
  260. * 读二维码并输出携带的信息
  261. * @param file 文件
  262. * @return
  263. * @throws IOException
  264. * @throws ReaderException
  265. */
  266. public static Result readQrCode(File file) throws IOException, ReaderException {
  267. return readQrCode(new FileInputStream(file));
  268. }
  269. public static void main(String... args) throws IOException, WriterException, ReaderException {
  270. String fileFullPath = "/Users/baby/work/tmp/qrcode28.gif";
  271. String logoPath = "/Users/baby/work/tmp/mylogo.jpeg";
  272. String content = "中国人,你啊好!";
  273. // createQrCodeAndLogo(fileFullPath, logoPath, content, 430, 430, "gif");
  274. String content1 = "中华人民共和国";
  275. // content = "WE1231238239128sASDASDSADSDWEWWREWRERWSDFDFSDSDF123123123123213123";
  276. // createQrCode(fileFullPath, content,900, "JPEG");
  277. // Result result = readQrCode(fileFullPath);
  278. // System.err.println("result.toString => " + result.toString());
  279. // String text = result.getText();
  280. // System.err.println("text => " + text);
  281. //
  282. // fileFullPath = "/Users/baby/work/tmp/qrcode29.jpg";
  283. createQrCode(fileFullPath, content,900, "JPEG");
  284. // Result result1 = readQrCode(fileFullPath);
  285. // System.err.println("text1 => " + result1.getText());
  286. //
  287. // fileFullPath = "/Users/baby/work/tmp/qrcode51.jpg"; // 使用QrCode.jar生成的二维码
  288. // Result result2 = readQrCode(fileFullPath);
  289. // System.err.println("text2 => " + result2.getText());
  290. fileFullPath = "C:\\work\\test\\qrcode03.png";
  291. fileFullPath = "/Users/baby/work/upload/qrcode/wx-hello2.png";
  292. Result result3 = readQrCode(fileFullPath);
  293. System.err.println("result3 => " + result3.getText());
  294. String url = "https://images2015.cnblogs.com/blog/755171/201610/755171-20161012154826406-1901968056.png";
  295. Result result4 = readQrCodeByUrl(url);
  296. System.err.println("result4 => " + result4.getText());
  297. content = "{name: '张三', nickname: '张三', age: 23}";
  298. String codeFileName = "C:\\work\\test\\qrcode04.png";
  299. String logoFileName = "C:\\work\\test\\logo.jpg";
  300. codeFileName = "/Users/baby/work/upload/qrcode/qrcode60.jpg";
  301. logoFileName = "/Users/baby/work/tmp/mylogo.jpeg";
  302. // createQrCodeAndLogo(codeFileName, logoFileName, content,
  303. // 430, 430, FileType.PNG.getSuffix());
  304. Result result5 = readQrCode(codeFileName);
  305. System.err.println("result5 => " + result5.getText());
  306. //如果是完整的链接,基本会自动跳转到相应的页面
  307. /*content = "https://www.baidu.com";
  308. codeFileName = "/Users/baby/work/upload/qrcode/qrcode-lianjie.png";
  309. createQrCodeAndLogo(codeFileName, logoFileName, content,
  310. 430, 430, FileType.PNG.getSuffix());*/
  311. }
  312. }

 The End。

 

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/小蓝xlanll/article/detail/715806
推荐阅读
相关标签
  

闽ICP备14008679号