矩形二维码生成,解析(彩色、多个)

2024-05-14 14:18

本文主要是介绍矩形二维码生成,解析(彩色、多个),希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

矩形二维码生成,解析(彩色、多个)

说明

  1. java生成普通二维码、带logo二维码、彩色二维码
  2. java解析彩色、多个二维码(一个图片上的多个二维码)
使用到的第三方jar包如下:
com.google.zxing:core:3.4.0
com.google.zxing:javase:3.4.0
生成二维码
package com.utils;import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.multi.qrcode.QRCodeMultiReader;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.AffineTransformOp;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.HashMap;@Slf4j
public class QRUtil {private static final String CHARSET = "UTF-8";private static final String FORMAT = "PNG";// 二维码尺寸private static final int QRCODE_SIZE = 150;// logo宽高private static final int LOGO_SIZE = 50;private static final HashMap<EncodeHintType, Object> ENCODE_HINTS = new HashMap<>();private static final HashMap<DecodeHintType, Object> DECODE_HINTS = new HashMap<>();static {ENCODE_HINTS.put(EncodeHintType.CHARACTER_SET, CHARSET);ENCODE_HINTS.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M);ENCODE_HINTS.put(EncodeHintType.MARGIN, 1);DECODE_HINTS.put(DecodeHintType.CHARACTER_SET, CHARSET);}/*** 生成二维码** @param content  内容* @param destPath 存储地址*/public static void encode(String content, String destPath) {encode(content, null, destPath);}/*** 生成二维码(包含logo)** @param content  内容* @param logoPath logo地址* @param destPath 存储地址*/public static void encode(String content, String logoPath, String destPath) {try {BufferedImage img = bufferedImage(content, logoPath);if (img != null) {ImageIO.write(img, FORMAT, new File(destPath));}} catch (IOException ignored) {}}/*** 生成二维码(包含logo)** @param content  内容* @param logoPath logo地址*/public static BufferedImage encodeBuffer(String content, String logoPath) {return bufferedImage(content, logoPath);}private static BufferedImage bufferedImage(String content, String logoPath) {BitMatrix bitMatrix = null;try {bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE, ENCODE_HINTS);} catch (WriterException ignored) {}if (bitMatrix == null) {return null;}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) ? Color.BLACK.getRGB() : Color.WHITE.getRGB());}}if (!StringUtils.isEmpty(logoPath)) {// 插入logoinsertLogo(image, logoPath);}return image;}private static void insertLogo(BufferedImage source, String logoPath) {File file = new File(logoPath);if (!file.exists()) {return;}try {BufferedImage srcImage = ImageIO.read(file);int width = srcImage.getWidth(null);int height = srcImage.getHeight(null);Image destImage = srcImage.getScaledInstance(LOGO_SIZE, LOGO_SIZE, Image.SCALE_SMOOTH);// 按比例缩放logo图片if ((height > LOGO_SIZE) || (width > LOGO_SIZE)) {double ratio;if (height > width) {ratio = Integer.valueOf(LOGO_SIZE).doubleValue() / height;} else {ratio = Integer.valueOf(LOGO_SIZE).doubleValue() / width;}AffineTransformOp op = new AffineTransformOp(AffineTransform.getScaleInstance(ratio, ratio), null);destImage = op.filter(srcImage, null);}width = destImage.getWidth(null);height = destImage.getHeight(null);BufferedImage tag = new BufferedImage(width - 5, height - 5, BufferedImage.TYPE_INT_RGB);Graphics g = tag.getGraphics();g.drawImage(destImage, 0, 0, null);g.dispose();destImage = tag;Graphics2D graph = source.createGraphics();int x = (QRCODE_SIZE - width) / 2;int y = (QRCODE_SIZE - height) / 2;graph.drawImage(destImage, x, y, width, height, null);Shape shape = new RoundRectangle2D.Float(x, y, width, width, 5, 5);graph.setStroke(new BasicStroke(1f));graph.draw(shape);graph.dispose();} catch (IOException e) {log.error("read img error", e);}}}
解析二维码
zxing自带的二值化(HybridBinarizer与GlobalHistogramBinarizer)并不能解决问题
因此要手动实现一下,解析二维码的主要流程:
1.将图片灰度化,使用加权灰度法(效果与opencv基本一致),尝试一次解析,失败则继续
2.对图片二值化(与opencv有差异,毕竟算法比不过它,暂时够用)
3.更换二值化阈值多次解析
    /*** 解析二维码** @param url 图片地址* @return 解析失败时返回null*/public static Result decode(String url, boolean handle) {try {BufferedImage image = ImageIO.read(new File(url));if (image != null) {int[][] pointGray = new int[image.getWidth()][image.getHeight()];if (handle) {image = gray(image, pointGray);Result result = decode(image);String content = result == null ? null : result.getText();if (!StringUtils.isEmpty(content)) {log.debug("The img decode success by only gray,[url:{}]", url);return result;}int threshold = 170;// 更换阈值多次解析for (int i = 0; i < 80; i += 5) {image = binary(image, pointGray, threshold + i);result = decode(image);content = result == null ? null : result.getText();if (!StringUtils.isEmpty(content)) {log.debug("The img decode success,[url:{}],[threshold:{}]", url, threshold + i);break;}}return result;}return decode(image);}} catch (IOException e) {log.error("read img error", e);}return null;}/*** 解析同一张图片的多个二维码** @param url 图片地址* @return 解析结果,失败时返回空数组*/public static Result[] decodeMulti(String url, boolean handle) {try {BufferedImage image = ImageIO.read(new File(url));if (image != null) {int[][] pointGray = new int[image.getWidth()][image.getHeight()];if (handle) {image = gray(image, pointGray);Result[] results = decodeMulti(image);if (results.length > 0) {log.debug("The img decode success by only gray,[url:{}]", url);return results;}int threshold = 170;// 更换阈值多次解析for (int i = 0; i < 80; i += 5) {image = binary(image, pointGray, threshold + i);results = decodeMulti(image);if (results.length > 0) {log.debug("The img decode success,[url:{}],[threshold:{}]", url, threshold + i);break;}}return results;}return decodeMulti(image);}} catch (IOException e) {log.error("read img error", e);}return new Result[0];}private static Result decode(BufferedImage image) {try {BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));return new MultiFormatReader().decode(bitmap, DECODE_HINTS);} catch (NotFoundException ignored) {}return null;}private static Result[] decodeMulti(BufferedImage image) {try {BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));return new QRCodeMultiReader().decodeMultiple(bitmap, DECODE_HINTS);} catch (NotFoundException ignored) {}return new Result[0];}/*** 加权灰度化** @param image 待处理图片* @return 灰度后的图片*/public static BufferedImage gray(BufferedImage image, int[][] pointGray) {int width = image.getWidth();int height = image.getHeight();BufferedImage grayImage = new BufferedImage(width, height, image.getType());for (int i = 0; i < width; i++) {for (int j = 0; j < height; j++) {final int color = image.getRGB(i, j);final int r = (color >> 16) & 0xff;final int g = (color >> 8) & 0xff;final int b = color & 0xff;int gray = (int) (0.3 * r + 0.59 * g + 0.11 * b);pointGray[i][j] = gray;int newPixel = colorToRgb(gray, gray, gray);grayImage.setRGB(i, j, newPixel);}}return grayImage;}private static int colorToRgb(int red, int green, int blue) {int newPixel = 0;newPixel += 255;newPixel = newPixel << 8;newPixel += red;newPixel = newPixel << 8;newPixel += green;newPixel = newPixel << 8;newPixel += blue;return newPixel;}/*** 二值化** @param image     原图片* @param threshold 阈值*/public static BufferedImage binary(BufferedImage image, int[][] pointGray, int threshold) {int width = image.getWidth();int height = image.getHeight();BufferedImage target = new BufferedImage(width, height, BufferedImage.TYPE_BYTE_BINARY);for (int x = 0; x < width; x++) {for (int y = 0; y < height; y++) {// 自己+周围8个点的相对灰度值int i = avgColor(pointGray, x, y, width, height);if (i > threshold) {target.setRGB(x, y, Color.WHITE.getRGB());} else {target.setRGB(x, y, Color.BLACK.getRGB());}}}return target;}public static int avgColor(int[][] gray, int x, int y, int w, int h) {int rs = gray[x][y]+ (x == 0 ? 255 : gray[x - 1][y])+ (x == 0 || y == 0 ? 255 : gray[x - 1][y - 1])+ (x == 0 || y == h - 1 ? 255 : gray[x - 1][y + 1])+ (y == 0 ? 255 : gray[x][y - 1])+ (y == h - 1 ? 255 : gray[x][y + 1])+ (x == w - 1 ? 255 : gray[x + 1][y])+ (x == w - 1 || y == 0 ? 255 : gray[x + 1][y - 1])+ (x == w - 1 || y == h - 1 ? 255 : gray[x + 1][y + 1]);return rs / 9;}

这篇关于矩形二维码生成,解析(彩色、多个)的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/988966

相关文章

线上Java OOM问题定位与解决方案超详细解析

《线上JavaOOM问题定位与解决方案超详细解析》OOM是JVM抛出的错误,表示内存分配失败,:本文主要介绍线上JavaOOM问题定位与解决方案的相关资料,文中通过代码介绍的非常详细,需要的朋... 目录一、OOM问题核心认知1.1 OOM定义与技术定位1.2 OOM常见类型及技术特征二、OOM问题定位工具

Java使用Javassist动态生成HelloWorld类

《Java使用Javassist动态生成HelloWorld类》Javassist是一个非常强大的字节码操作和定义库,它允许开发者在运行时创建新的类或者修改现有的类,本文将简单介绍如何使用Javass... 目录1. Javassist简介2. 环境准备3. 动态生成HelloWorld类3.1 创建CtC

深度解析Python中递归下降解析器的原理与实现

《深度解析Python中递归下降解析器的原理与实现》在编译器设计、配置文件处理和数据转换领域,递归下降解析器是最常用且最直观的解析技术,本文将详细介绍递归下降解析器的原理与实现,感兴趣的小伙伴可以跟随... 目录引言:解析器的核心价值一、递归下降解析器基础1.1 核心概念解析1.2 基本架构二、简单算术表达

深度解析Java @Serial 注解及常见错误案例

《深度解析Java@Serial注解及常见错误案例》Java14引入@Serial注解,用于编译时校验序列化成员,替代传统方式解决运行时错误,适用于Serializable类的方法/字段,需注意签... 目录Java @Serial 注解深度解析1. 注解本质2. 核心作用(1) 主要用途(2) 适用位置3

Java MCP 的鉴权深度解析

《JavaMCP的鉴权深度解析》文章介绍JavaMCP鉴权的实现方式,指出客户端可通过queryString、header或env传递鉴权信息,服务器端支持工具单独鉴权、过滤器集中鉴权及启动时鉴权... 目录一、MCP Client 侧(负责传递,比较简单)(1)常见的 mcpServers json 配置

从原理到实战解析Java Stream 的并行流性能优化

《从原理到实战解析JavaStream的并行流性能优化》本文给大家介绍JavaStream的并行流性能优化:从原理到实战的全攻略,本文通过实例代码给大家介绍的非常详细,对大家的学习或工作具有一定的... 目录一、并行流的核心原理与适用场景二、性能优化的核心策略1. 合理设置并行度:打破默认阈值2. 避免装箱

Maven中生命周期深度解析与实战指南

《Maven中生命周期深度解析与实战指南》这篇文章主要为大家详细介绍了Maven生命周期实战指南,包含核心概念、阶段详解、SpringBoot特化场景及企业级实践建议,希望对大家有一定的帮助... 目录一、Maven 生命周期哲学二、default生命周期核心阶段详解(高频使用)三、clean生命周期核心阶

Python从Word文档中提取图片并生成PPT的操作代码

《Python从Word文档中提取图片并生成PPT的操作代码》在日常办公场景中,我们经常需要从Word文档中提取图片,并将这些图片整理到PowerPoint幻灯片中,手动完成这一任务既耗时又容易出错,... 目录引言背景与需求解决方案概述代码解析代码核心逻辑说明总结引言在日常办公场景中,我们经常需要从 W

深入解析C++ 中std::map内存管理

《深入解析C++中std::map内存管理》文章详解C++std::map内存管理,指出clear()仅删除元素可能不释放底层内存,建议用swap()与空map交换以彻底释放,针对指针类型需手动de... 目录1️、基本清空std::map2️、使用 swap 彻底释放内存3️、map 中存储指针类型的对象

Java Scanner类解析与实战教程

《JavaScanner类解析与实战教程》JavaScanner类(java.util包)是文本输入解析工具,支持基本类型和字符串读取,基于Readable接口与正则分隔符实现,适用于控制台、文件输... 目录一、核心设计与工作原理1.底层依赖2.解析机制A.核心逻辑基于分隔符(delimiter)和模式匹