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

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

相关文章

PostgreSQL的扩展dict_int应用案例解析

《PostgreSQL的扩展dict_int应用案例解析》dict_int扩展为PostgreSQL提供了专业的整数文本处理能力,特别适合需要精确处理数字内容的搜索场景,本文给大家介绍PostgreS... 目录PostgreSQL的扩展dict_int一、扩展概述二、核心功能三、安装与启用四、字典配置方法

深度解析Java DTO(最新推荐)

《深度解析JavaDTO(最新推荐)》DTO(DataTransferObject)是一种用于在不同层(如Controller层、Service层)之间传输数据的对象设计模式,其核心目的是封装数据,... 目录一、什么是DTO?DTO的核心特点:二、为什么需要DTO?(对比Entity)三、实际应用场景解析

深度解析Java项目中包和包之间的联系

《深度解析Java项目中包和包之间的联系》文章浏览阅读850次,点赞13次,收藏8次。本文详细介绍了Java分层架构中的几个关键包:DTO、Controller、Service和Mapper。_jav... 目录前言一、各大包1.DTO1.1、DTO的核心用途1.2. DTO与实体类(Entity)的区别1

Java中的雪花算法Snowflake解析与实践技巧

《Java中的雪花算法Snowflake解析与实践技巧》本文解析了雪花算法的原理、Java实现及生产实践,涵盖ID结构、位运算技巧、时钟回拨处理、WorkerId分配等关键点,并探讨了百度UidGen... 目录一、雪花算法核心原理1.1 算法起源1.2 ID结构详解1.3 核心特性二、Java实现解析2.

使用Python绘制3D堆叠条形图全解析

《使用Python绘制3D堆叠条形图全解析》在数据可视化的工具箱里,3D图表总能带来眼前一亮的效果,本文就来和大家聊聊如何使用Python实现绘制3D堆叠条形图,感兴趣的小伙伴可以了解下... 目录为什么选择 3D 堆叠条形图代码实现:从数据到 3D 世界的搭建核心代码逐行解析细节优化应用场景:3D 堆叠图

深度解析Python装饰器常见用法与进阶技巧

《深度解析Python装饰器常见用法与进阶技巧》Python装饰器(Decorator)是提升代码可读性与复用性的强大工具,本文将深入解析Python装饰器的原理,常见用法,进阶技巧与最佳实践,希望可... 目录装饰器的基本原理函数装饰器的常见用法带参数的装饰器类装饰器与方法装饰器装饰器的嵌套与组合进阶技巧

解析C++11 static_assert及与Boost库的关联从入门到精通

《解析C++11static_assert及与Boost库的关联从入门到精通》static_assert是C++中强大的编译时验证工具,它能够在编译阶段拦截不符合预期的类型或值,增强代码的健壮性,通... 目录一、背景知识:传统断言方法的局限性1.1 assert宏1.2 #error指令1.3 第三方解决

全面解析MySQL索引长度限制问题与解决方案

《全面解析MySQL索引长度限制问题与解决方案》MySQL对索引长度设限是为了保持高效的数据检索性能,这个限制不是MySQL的缺陷,而是数据库设计中的权衡结果,下面我们就来看看如何解决这一问题吧... 目录引言:为什么会有索引键长度问题?一、问题根源深度解析mysql索引长度限制原理实际场景示例二、五大解决

深度解析Spring Boot拦截器Interceptor与过滤器Filter的区别与实战指南

《深度解析SpringBoot拦截器Interceptor与过滤器Filter的区别与实战指南》本文深度解析SpringBoot中拦截器与过滤器的区别,涵盖执行顺序、依赖关系、异常处理等核心差异,并... 目录Spring Boot拦截器(Interceptor)与过滤器(Filter)深度解析:区别、实现

深度解析Spring AOP @Aspect 原理、实战与最佳实践教程

《深度解析SpringAOP@Aspect原理、实战与最佳实践教程》文章系统讲解了SpringAOP核心概念、实现方式及原理,涵盖横切关注点分离、代理机制(JDK/CGLIB)、切入点类型、性能... 目录1. @ASPect 核心概念1.1 AOP 编程范式1.2 @Aspect 关键特性2. 完整代码实