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

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

相关文章

python常见环境管理工具超全解析

《python常见环境管理工具超全解析》在Python开发中,管理多个项目及其依赖项通常是一个挑战,下面:本文主要介绍python常见环境管理工具的相关资料,文中通过代码介绍的非常详细,需要的朋友... 目录1. conda2. pip3. uvuv 工具自动创建和管理环境的特点4. setup.py5.

全面解析HTML5中Checkbox标签

《全面解析HTML5中Checkbox标签》Checkbox是HTML5中非常重要的表单元素之一,通过合理使用其属性和样式自定义方法,可以为用户提供丰富多样的交互体验,这篇文章给大家介绍HTML5中C... 在html5中,Checkbox(复选框)是一种常用的表单元素,允许用户在一组选项中选择多个项目。本

Python包管理工具核心指令uvx举例详细解析

《Python包管理工具核心指令uvx举例详细解析》:本文主要介绍Python包管理工具核心指令uvx的相关资料,uvx是uv工具链中用于临时运行Python命令行工具的高效执行器,依托Rust实... 目录一、uvx 的定位与核心功能二、uvx 的典型应用场景三、uvx 与传统工具对比四、uvx 的技术实

SpringBoot排查和解决JSON解析错误(400 Bad Request)的方法

《SpringBoot排查和解决JSON解析错误(400BadRequest)的方法》在开发SpringBootRESTfulAPI时,客户端与服务端的数据交互通常使用JSON格式,然而,JSON... 目录问题背景1. 问题描述2. 错误分析解决方案1. 手动重新输入jsON2. 使用工具清理JSON3.

使用jenv工具管理多个JDK版本的方法步骤

《使用jenv工具管理多个JDK版本的方法步骤》jenv是一个开源的Java环境管理工具,旨在帮助开发者在同一台机器上轻松管理和切换多个Java版本,:本文主要介绍使用jenv工具管理多个JD... 目录一、jenv到底是干啥的?二、jenv的核心功能(一)管理多个Java版本(二)支持插件扩展(三)环境隔

Redis过期删除机制与内存淘汰策略的解析指南

《Redis过期删除机制与内存淘汰策略的解析指南》在使用Redis构建缓存系统时,很多开发者只设置了EXPIRE但却忽略了背后Redis的过期删除机制与内存淘汰策略,下面小编就来和大家详细介绍一下... 目录1、简述2、Redis http://www.chinasem.cn的过期删除策略(Key Expir

Go学习记录之runtime包深入解析

《Go学习记录之runtime包深入解析》Go语言runtime包管理运行时环境,涵盖goroutine调度、内存分配、垃圾回收、类型信息等核心功能,:本文主要介绍Go学习记录之runtime包的... 目录前言:一、runtime包内容学习1、作用:① Goroutine和并发控制:② 垃圾回收:③ 栈和

Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析

《Spring组件实例化扩展点之InstantiationAwareBeanPostProcessor使用场景解析》InstantiationAwareBeanPostProcessor是Spring... 目录一、什么是InstantiationAwareBeanPostProcessor?二、核心方法解

深入解析 Java Future 类及代码示例

《深入解析JavaFuture类及代码示例》JavaFuture是java.util.concurrent包中用于表示异步计算结果的核心接口,下面给大家介绍JavaFuture类及实例代码,感兴... 目录一、Future 类概述二、核心工作机制代码示例执行流程2. 状态机模型3. 核心方法解析行为总结:三

Python实现自动化Word文档样式复制与内容生成

《Python实现自动化Word文档样式复制与内容生成》在办公自动化领域,高效处理Word文档的样式和内容复制是一个常见需求,本文将展示如何利用Python的python-docx库实现... 目录一、为什么需要自动化 Word 文档处理二、核心功能实现:样式与表格的深度复制1. 表格复制(含样式与内容)2