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

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

相关文章

Agent开发核心技术解析以及现代Agent架构设计

《Agent开发核心技术解析以及现代Agent架构设计》在人工智能领域,Agent并非一个全新的概念,但在大模型时代,它被赋予了全新的生命力,简单来说,Agent是一个能够自主感知环境、理解任务、制定... 目录一、回归本源:到底什么是Agent?二、核心链路拆解:Agent的"大脑"与"四肢"1. 规划模

MySQL字符串转数值的方法全解析

《MySQL字符串转数值的方法全解析》在MySQL开发中,字符串与数值的转换是高频操作,本文从隐式转换原理、显式转换方法、典型场景案例、风险防控四个维度系统梳理,助您精准掌握这一核心技能,需要的朋友可... 目录一、隐式转换:自动但需警惕的&ld编程quo;双刃剑”二、显式转换:三大核心方法详解三、典型场景

Java使用Spire.Barcode for Java实现条形码生成与识别

《Java使用Spire.BarcodeforJava实现条形码生成与识别》在现代商业和技术领域,条形码无处不在,本教程将引导您深入了解如何在您的Java项目中利用Spire.Barcodefor... 目录1. Spire.Barcode for Java 简介与环境配置2. 使用 Spire.Barco

C#实现将Excel工作表拆分为多个窗格

《C#实现将Excel工作表拆分为多个窗格》在日常工作中,我们经常需要处理包含大量数据的Excel文件,本文将深入探讨如何在C#中利用强大的Spire.XLSfor.NET自动化实现Excel工作表的... 目录为什么需要拆分 Excel 窗格借助 Spire.XLS for .NET 实现冻结窗格(Fro

SQL 注入攻击(SQL Injection)原理、利用方式与防御策略深度解析

《SQL注入攻击(SQLInjection)原理、利用方式与防御策略深度解析》本文将从SQL注入的基本原理、攻击方式、常见利用手法,到企业级防御方案进行全面讲解,以帮助开发者和安全人员更系统地理解... 目录一、前言二、SQL 注入攻击的基本概念三、SQL 注入常见类型分析1. 基于错误回显的注入(Erro

SpringBoot集成iText快速生成PDF教程

《SpringBoot集成iText快速生成PDF教程》本文介绍了如何在SpringBoot项目中集成iText9.4.0生成PDF文档,包括新特性的介绍、环境准备、Service层实现、Contro... 目录SpringBoot集成iText 9.4.0生成PDF一、iText 9新特性与架构变革二、环

idea-java序列化serialversionUID自动生成方式

《idea-java序列化serialversionUID自动生成方式》Java的Serializable接口用于实现对象的序列化和反序列化,通过将对象转换为字节流来存储或传输,实现Serializa... 目录简介实现序列化serialVersionUID配置使用总结简介Java.io.Seripyth

C++ 多态性实战之何时使用 virtual 和 override的问题解析

《C++多态性实战之何时使用virtual和override的问题解析》在面向对象编程中,多态是一个核心概念,很多开发者在遇到override编译错误时,不清楚是否需要将基类函数声明为virt... 目录C++ 多态性实战:何时使用 virtual 和 override?引言问题场景判断是否需要多态的三个关

Java中的随机数生成案例从范围字符串到动态区间应用

《Java中的随机数生成案例从范围字符串到动态区间应用》本文介绍了在Java中生成随机数的多种方法,并通过两个案例解析如何根据业务需求生成特定范围的随机数,本文通过两个实际案例详细介绍如何在java中... 目录Java中的随机数生成:从范围字符串到动态区间应用引言目录1. Java中的随机数生成基础基本随

C#自动化生成PowerPoint(PPT)演示文稿

《C#自动化生成PowerPoint(PPT)演示文稿》在当今快节奏的商业环境中,演示文稿是信息传递和沟通的关键工具,下面我们就深入探讨如何利用C#和Spire.Presentationfor.NET... 目录环境准备与Spire.Presentation安装核心操作:添加与编辑幻灯片元素添加幻灯片文本操