Java解析生成二维码

1.pom.xml依赖

<!--        引入二维码相关的依赖--><dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.3.3</version></dependency><dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.3.3</version></dependency>

2. BufferedImageLuminanceSource.java

package com.rfos.assistsilkworm.util;import com.google.zxing.LuminanceSource;
import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;/*** @Author rfos* @Date 2022/11/6 19:39* @Description TODO Google提供的二维码辅助类*/
public class BufferedImageLuminanceSource extends LuminanceSource {private final BufferedImage image;private final int left;private final int top;public BufferedImageLuminanceSource(BufferedImage image) {this(image, 0, 0, image.getWidth(), image.getHeight());}public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {super(width, height);int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();if (left + width > sourceWidth || top + height > sourceHeight) {throw new IllegalArgumentException("Crop rectangle does not fit within image data.");}for (int y = top; y < top + height; y++) {for (int x = left; x < left + width; x++) {if ((image.getRGB(x, y) & 0xFF000000) == 0) {image.setRGB(x, y, 0xFFFFFFFF); // = white}}}this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);this.image.getGraphics().drawImage(image, 0, 0, null);this.left = left;this.top = top;}public byte[] getRow(int y, byte[] row) {if (y < 0 || y >= getHeight()) {throw new IllegalArgumentException("Requested row is outside the image: " + y);}int width = getWidth();if (row == null || row.length < width) {row = new byte[width];}image.getRaster().getDataElements(left, top + y, width, 1, row);return row;}public byte[] getMatrix() {int width = getWidth();int height = getHeight();int area = width * height;byte[] matrix = new byte[area];image.getRaster().getDataElements(left, top, width, height, matrix);return matrix;}public boolean isCropSupported() {return true;}public LuminanceSource crop(int left, int top, int width, int height) {return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);}public boolean isRotateSupported() {return true;}public LuminanceSource rotateCounterClockwise() {int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);Graphics2D g = rotatedImage.createGraphics();g.drawImage(image, transform, null);g.dispose();int width = getWidth();return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);}}

3. QRCodeImageUtils工具类

package com.rfos.assistsilkworm.util;
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.util.Hashtable;
import java.util.Random;
import javax.imageio.ImageIO;import com.google.zxing.*;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import com.rfos.assistsilkworm.constant.CommonConstants;/*** @Author rfos* @Date 2022/11/6 19:38* @Description TODO 二维码相关工具类*/public class QRCodeImageUtils {private static final String CHARSET = "utf-8";private static final String FORMAT_NAME = "JPG";// 二维码尺寸private static final int QRCODE_SIZE = 300;// LOGO宽度private static final int WIDTH = 60;// LOGO高度private static final int HEIGHT = 60;private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {Hashtable hints = new Hashtable();hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);hints.put(EncodeHintType.CHARACTER_SET, CHARSET);hints.put(EncodeHintType.MARGIN, 1);BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,hints);int width = bitMatrix.getWidth();int height = bitMatrix.getHeight();BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);for (int x = 0; x < width; x++) {for (int y = 0; y < height; y++) {image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);}}if (imgPath == null || "".equals(imgPath)) {return image;}// 插入图片QRCodeImageUtils.insertImage(image, imgPath, needCompress);return image;}private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {File file = new File(imgPath);if (!file.exists()) {System.err.println("" + imgPath + "   该文件不存在!");return;}Image src = ImageIO.read(new File(imgPath));int width = src.getWidth(null);int height = src.getHeight(null);// 压缩LOGOif (needCompress) {if (width > WIDTH) {width = WIDTH;}if (height > HEIGHT) {height = HEIGHT;}Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);Graphics g = tag.getGraphics();// 绘制缩小后的图g.drawImage(image, 0, 0, null);g.dispose();src = image;}// 插入LOGOGraphics2D graph = source.createGraphics();int x = (QRCODE_SIZE - width) / 2;int y = (QRCODE_SIZE - height) / 2;graph.drawImage(src, x, y, width, height, null);Shape shape = new RoundRectangle2D.Float(x, y, width, width, 6, 6);graph.setStroke(new BasicStroke(3f));graph.draw(shape);graph.dispose();}public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {BufferedImage image = QRCodeImageUtils.createImage(content, imgPath, needCompress);mkdirs(destPath);// String file = new Random().nextInt(99999999)+".jpg";// ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));ImageIO.write(image, FORMAT_NAME, new File(destPath));}public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {BufferedImage image = QRCodeImageUtils.createImage(content, imgPath, needCompress);return image;}public static void mkdirs(String destPath) {File file = new File(destPath);// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)if (!file.exists() && !file.isDirectory()) {file.mkdirs();}}public static void encode(String content, String imgPath, String destPath) throws Exception {QRCodeImageUtils.encode(content, imgPath, destPath, false);}// 被注释的方法/** public static void encode(String content, String destPath, boolean* needCompress) throws Exception { QRCodeImageUtils.encode(content, null, destPath,* needCompress); }*/public static void encode(String content, String destPath) throws Exception {QRCodeImageUtils.encode(content, null, destPath, false);}public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)throws Exception {BufferedImage image = QRCodeImageUtils.createImage(content, imgPath, needCompress);ImageIO.write(image, FORMAT_NAME, output);}/*** 生成二维码* @param content* @param output* @throws Exception*/public static void encode(String content, OutputStream output) throws Exception {QRCodeImageUtils.encode(content, null, output, false);}/*** 解析二维码* @param file* @return* @throws Exception*/public static String decode(File file) throws Exception {BufferedImage image;image = ImageIO.read(file);if (image == null) {return null;}BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));Result result;Hashtable hints = new Hashtable();hints.put(DecodeHintType.CHARACTER_SET, CHARSET);result = new MultiFormatReader().decode(bitmap, hints);String resultStr = result.getText();return resultStr;}public static String decode(String path) throws Exception {return QRCodeImageUtils.decode(new File(path));}/*** 下载二维码至本地-无log* @param text 文本内容* @param width 宽度* @param height 高度* @param filePath 文件路径*/private static void generateQRCodeImageToLocal(String text, int width, int height, String filePath){try {QRCodeWriter qrCodeWriter = new QRCodeWriter();BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);Path path = FileSystems.getDefault().getPath(filePath);MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);} catch (WriterException e) {System.out.println("Could not generate QR Code, WriterException :: " + e.getMessage());} catch (IOException e) {System.out.println("Could not generate QR Code, IOException :: " + e.getMessage());}}/*** 测试生成解析二维码* @param args* @throws Exception*/public static void main(String[] args) throws Exception {String text = "RFOS";// 嵌入二维码的图片路径String imgPath = CommonConstants.ASSIST_SILKWORM_LOG;// 生成的二维码的路径及名称String destPath = CommonConstants.QR_CODE_IMAGE_PATH;//生成二维码QRCodeImageUtils.encode(text, imgPath, destPath, true);// 解析二维码String str = QRCodeImageUtils.decode(destPath);// 打印出解析出的内容System.out.println(str);}
}

Java解析生成二维码-log相关推荐

  1. 在java中生成二维码,并直接输出到jsp页面

    在java中生成的二维码不存到磁盘里要直接输出到页面上,这就需要把生成的二维码直接以流的形式输出到页面上,我用的是myeclipse 和 tomcat 它的原理是:在加载页面时,根据img的src(c ...

  2. java实现生成二维码及扫码登录

    java实现生成二维码及扫码登录 1. 场景描述 2. 实现思路 3. 代码实现过程 3.1 pom.xml 3.2 二维码工具类 3.3 生成二维码并下载为图片 3.4 扫码登录 1. 场景描述   ...

  3. java零碎要点---用java实现生成二维码,与解析代码实现

    创梦综合技术qq交流群:CreDream:251572072 二维码,是一种采用黑白相间的平面几何图形通过相应的编码算法来记录文字.图片.网址等信息的条码图片.如下图 二维码的特点: 1.  高密度编 ...

  4. java springMVC生成二维码

    Zxing是Google提供的工具,提供了二维码的生成与解析的方法,现在使用Java利用Zxing生成二维码 1),二维码的生成 将Zxing-core.jar 包加入到classpath下. 我的下 ...

  5. Java自动生成二维码总结

    推荐一篇博客:Java自动生成带log的二维码 https://mp.csdn.net/postedit/84454677 第一种简单的方法: import java.io.File; import ...

  6. java后台生成二维码以及页面显示二维码方式

    上篇文章已经说明并发布了后台生成二维码工具类,大家可以直接去看或者去拿. 地址:最简单实用的java生成二维码工具 现在呢说明页面上展示二维码的两种方式: 1.使用img标签的src来请求生成二维码, ...

  7. java实现生成二维码

    1.引入 maven 坐标 <!--Java 生成二维码 --><dependency><groupId>com.google.zxing</groupId& ...

  8. Java后端生成二维码(QrCode)

    引入依赖 <!-- 生成二维码所需依赖 --><dependency><groupId>commons-lang</groupId><artifa ...

  9. Java自定义生成二维码(兼容你所有的需求)

    1.概述 作为Java开发人员,说到生成二维码就会想到zxing开源二维码图像处理库,不可否认的是zxing确实很强大,但是实际需求中会遇到各种各样的需求是zxing满足不了的,于是就有了想法自己扩展 ...

最新文章

  1. 利用硅光子学的移动心脏监护仪
  2. Hadoop HA 深度解析
  3. php mysql try catch_PHP的try catch有多大意义?
  4. android 通知显示时间,android:在特定时间显示通知?
  5. jboss4 迁移_应用程序服务器迁移:从JBoss EE5到Wildfly EE7
  6. 感知器 机器学习_机器学习感知器实现
  7. 服务器怎么关闭终端依然运行node,关闭控制台后如何永久运行node.js应用程序?...
  8. 汉字字符编码的科普笔记(GB2312汉字编码,Unicode与UTF-8,字符映射表,vim,文泉驿,正则表达式)
  9. 载波同步matlab程序,Gardner算法实现基带信号位同步的原理和MATLAB程序讲解
  10. dB dBm概念及计算
  11. Bebras挑战样题之五——警察能抓住海盗吗?
  12. 提高新股中签率的技巧|新股中签技巧
  13. 网络传输的两种方式——同步传输和异步传输的区别
  14. docker镜像仓库habor1.10.0安装配置-单机版
  15. (莱昂氏unix源代码分析导读-19)再谈进程swtch
  16. 手机行业影像突破,谁能成为下一个“苹果”?
  17. 解读:电子合同四大理解误区
  18. 亚马逊云科技 BuildOn 第三季 【基于 Serverless 构建零售创新应用】过程介绍及个人思考及总结
  19. 文本中每行的部分文本格式由CamelWord的形式替换为CAMEL_WORD的形式
  20. C语言中+=的含义你明白吗?

热门文章

  1. 为什么薄膜干涉的厚度要很小_薄膜厚度对薄膜干涉现象的影响及其物理意义
  2. win10 计划 定时关机
  3. html+css制作属于自己的头像和简介
  4. layui表单数据重载 全局搜索
  5. Gmail Api 的解读及例子
  6. 图像处理与计算机视觉的论文创新点总结
  7. 计算机二级(二)仅学习
  8. oracle数据库电子书大全
  9. eclipse怎么联想输入_java联想输入
  10. 深入研究simulink建模与仿真之输入端口模块(Inport)的几种不同的图标