Java 使用zxing生成二维码

POM文件,引用

        <dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.1.0</version></dependency><dependency><groupId>com.google.zxing</groupId><artifactId>javase</artifactId><version>3.1.0</version></dependency>

工具类:

public class QRCodeUtil {private static final String CHARSET = "utf-8";private static final String FORMAT = "JPG";// 二维码尺寸private static final int QRCODE_SIZE = 300;// LOGO宽度private static final int LOGO_WIDTH = 60;// LOGO高度private static final int LOGO_HEIGHT = 60;private static BufferedImage createImage(String content, String logoPath, boolean needCompress) throws Exception {Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();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 (logoPath == null || "".equals(logoPath)) {return image;}// 插入图片QRCodeUtil.insertImage(image, logoPath, needCompress);return image;}/*** 插入LOGO** @param source*            二维码图片* @param logoPath*            LOGO图片地址* @param needCompress*            是否压缩* @throws Exception*/private static void insertImage(BufferedImage source, String logoPath, boolean needCompress) throws Exception {File file = new File(logoPath);if (!file.exists()) {throw new Exception("logo file not found.");}Image src = ImageIO.read(new File(logoPath));int width = src.getWidth(null);int height = src.getHeight(null);if (needCompress) { // 压缩LOGOif (width > LOGO_WIDTH) {width = LOGO_WIDTH;}if (height > LOGO_HEIGHT) {height = LOGO_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();}/*** 生成二维码(内嵌LOGO)* 二维码文件名随机,文件名可能会有重复** @param content*            内容* @param logoPath*            LOGO地址* @param destPath*            存放目录* @param needCompress*            是否压缩LOGO* @throws Exception*/public static String encode(String content, String logoPath, String destPath, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress);mkdirs(destPath);String fileName = new Random().nextInt(99999999) + "." + FORMAT.toLowerCase();ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));return fileName;}/*** 生成二维码(内嵌LOGO)* 调用者指定二维码文件名** @param content*            内容* @param logoPath*            LOGO地址* @param destPath*            存放目录* @param fileName*            二维码文件名* @param needCompress*            是否压缩LOGO* @throws Exception*/public static String encode(String content, String logoPath, String destPath, String fileName, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress);mkdirs(destPath);fileName = fileName.substring(0, fileName.indexOf(".")>0?fileName.indexOf("."):fileName.length())+ "." + FORMAT.toLowerCase();ImageIO.write(image, FORMAT, new File(destPath + "/" + fileName));return fileName;}/*** 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.* (mkdir如果父目录不存在则会抛出异常)* @param destPath*            存放目录*/public static void mkdirs(String destPath) {File file = new File(destPath);if (!file.exists() && !file.isDirectory()) {file.mkdirs();}}/*** 生成二维码(内嵌LOGO)** @param content*            内容* @param logoPath*            LOGO地址* @param destPath*            存储地址* @throws Exception*/public static String encode(String content, String logoPath, String destPath) throws Exception {return QRCodeUtil.encode(content, logoPath, destPath, false);}/*** 生成二维码** @param content*            内容* @param destPath*            存储地址* @param needCompress*            是否压缩LOGO* @throws Exception*/public static String encode(String content, String destPath, boolean needCompress) throws Exception {return QRCodeUtil.encode(content, null, destPath, needCompress);}/*** 生成二维码** @param content*            内容* @param destPath*            存储地址* @throws Exception*/public static String encode(String content, String destPath) throws Exception {return QRCodeUtil.encode(content, null, destPath, false);}/*** 生成二维码(内嵌LOGO)** @param content*            内容* @param logoPath*            LOGO地址* @param output*            输出流* @param needCompress*            是否压缩LOGO* @throws Exception*/public static void encode(String content, String logoPath, OutputStream output, boolean needCompress)throws Exception {BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress);ImageIO.write(image, FORMAT, output);}/*** 生成二维码** @param content*            内容* @param output*            输出流* @throws Exception*/public static void encode(String content, OutputStream output) throws Exception {QRCodeUtil.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<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();hints.put(DecodeHintType.CHARACTER_SET, CHARSET);result = new MultiFormatReader().decode(bitmap, hints);String resultStr = result.getText();return resultStr;}/*** 解析二维码** @param path*            二维码图片地址* @return* @throws Exception*/public static String decode(String path) throws Exception {return QRCodeUtil.decode(new File(path));}}

测试

    public static void main(String[] args) throws Exception {String text = "http://www.anyroad.com.cn";//不含Logo//QRCodeUtil.encode(text, null, "e:\\", true);//含Logo,不指定二维码图片名//QRCodeUtil.encode(text, "e:\\csdn.jpg", "e:\\", true);//含Logo,指定二维码图片名QRCodeUtil.encode(text, "", "/Users/yt/Documents/code/", "qrcode", true);}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.mzph.cn/news/191095.shtml

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

java 猜数字游戏

package com.gaoce;import java.util.Random; import java.util.Scanner;/*** ClassName: GuessNumber* Package: com.org* Description: 猜数字游戏* Author: H* Create: 2023/12/1 16:26* Version: 1.0*/public class GuessNumber {Random random new Random();public int r…

C++标准库类型string基本成员函数用法

标准库类型string&#xff0c;基本函数成员用法详细讲解 文章目录 标准库类型string&#xff0c;基本函数成员用法详细讲解一、头文件二、string构造函数三、string赋值函数assign四、string拼接函数append五、string查找函数 find和 rfind六、string替换函数 replace七、strin…

二叉树OJ题目——C语言

LeetCode 104.二叉树的最大深度 1. 题目描述&#xff1a; 给定一个二叉树 root &#xff0c;返回其最大深度。 二叉树的 最大深度 是指从根节点到最远叶子节点的最长路径上的节点数。 示例 1&#xff1a; 输入&#xff1a;root [3,9,20,null,null,15,7] 输出&#xff1a;3示例…

CSS浅谈动画性能

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 目的一、举个栗子二、性能分析1.从图层分析2.性能分析 总结 目的 为了探究使用动画时&#xff0c;『transform』和『width、height、margin等』的差异 一、举个栗子…

【1】基于多设计模式下的同步异步日志系统

1. 项目介绍 本项⽬主要实现⼀个⽇志系统&#xff0c; 其主要⽀持以下功能: • ⽀持多级别⽇志消息 • ⽀持同步⽇志和异步⽇志 • ⽀持可靠写⼊⽇志到控制台、⽂件以及滚动⽂件中 • ⽀持多线程程序并发写⽇志 • ⽀持扩展不同的⽇志落地⽬标地 2. 开发环境 • CentOS 7 • vs…

Prism.js实现代码高亮并添加行号

先上效果: Prism.js Prism 是一款轻量、可扩展的代码语法高亮库&#xff0c;使用现代化的 Web 标准构建。 使用 Prismjs 可以快速为网站添加代码高亮功能&#xff0c;支持超过113中编程语言&#xff0c;还支持多种插件&#xff0c;是简洁、高效的代码高亮解决方案。 为什么选…

C++跨目录include问题

不同文件夹下使用预处理器指示符#include 使用举例 假设我们有如下一个工程&#xff0c;其中包含了几个源代码和头文件&#xff0c;其中main.cpp是主源代码文件&#xff0c;里面含有main函数&#xff1a; 在foldder main中包含&#xff1a;func4.hpp&#xff0c;func4.cpp&am…

1.0 十大经典排序算法

分类 算法 本系列算法整理自&#xff1a;https://github.com/hustcc/JS-Sorting-Algorithm 同时也参考了维基百科做了一些补充。 排序算法是《数据结构与算法》中最基本的算法之一。 排序算法可以分为内部排序和外部排序&#xff0c;内部排序是数据记录在内存中进行排序&#…

Python遥感开发之批量镶嵌

Python遥感开发之批量镶嵌 0.ArcGis镶嵌1.Arcpy实现镶嵌1.1 Arcpy实现单个镶嵌1.2 Arcpy实现批量镶嵌 2.GDAL实现镶嵌 前言&#xff1a;主要介绍了遥感数据的镶嵌&#xff0c;其中包括使用ArcGis如何完成镶嵌&#xff0c;如何使用Arcpy和GDAL完成镶嵌。 0.ArcGis镶嵌 是ArcGis…

PyLMKit(2):快速开始大模型应用开发

快速开始 GitHub&#xff1a;https://github.com/52phm/pylmkitPyLMKit 官方教程 PyLMKit应用&#xff08;online application&#xff09;English document中文文档 0.下载安装 pip install -U pylmkit --user1.设置 API KEY 一个方便的方法是创建一个新的.env文件&#…

mysql中int(10)和char(10),varchar(10)区别是什么?

整体对比表格 int(10)char(10)varchar(10)存储方式二进制整数字符集编码的字符串字符集编码的字符串存储空间固定为4字节固定为10字节根据实际使用长度变化&#xff0c;通常更小存储内容整数字符串(用空格填充)字符串(不需要填充)比较大小整数的比较字符串的字典序比较字符串的…

物流单管理系统软件物流单打印,物流单打印模板,佳易王物流快运单管理软件下载

物流单管理系统软件物流单打印&#xff0c;物流单打印模板&#xff0c;佳易王物流快运单管理软件下载 软件试用版下载或技术支持可以点击最下方官网卡片 上图&#xff1a;在物流开单时&#xff0c;可以先输入电话&#xff0c;如果之前存在该托运人信息&#xff0c;则可以一键…

高德Map

使用 官网&#xff1a;JS API 结合Vue使用 npm i amap/amap-jsapi-loader --saveimport AMapLoader from amap/amap-jsapi-loader;marker的属性、事件、方法 https://lbs.amap.com/api/javascript-api-v2/documentation#marker 自定义marker 为创建的 Marker 指定自定义图…

Motion 5 for Mac,释放创意,打造精彩视频特效!

Motion 5 for Mac是一款强大的视频后期特效处理软件&#xff0c;为Mac用户提供了无限的创意可能性。无论你是专业的影视制作人&#xff0c;还是想为个人视频添加独特特效的爱好者&#xff0c;Motion 5都能满足你的需求&#xff0c;让你的视频脱颖而出。 Motion 5提供了丰富多样…

【滑动窗口】将X减到0的最小操作数

将X减到0的最小操作数 1658. 将 x 减到 0 的最小操作数 - 力扣&#xff08;LeetCode&#xff09; 文章目录 将X减到0的最小操作数题目描述算法原理代码编写Java代码编写C代码编写 题目描述 给你一个整数数组 nums 和一个整数 x 。每一次操作时&#xff0c;你应当移除数组 num…

webGIS使用JS,高德API完成的智慧校园项目路径规划

代码实现&#xff1a; //通过geojson对象来管理覆盖物&#xff0c;显示点geojson.addOverlay(marker)//保存数据&#xff08;将geojson对象转换成标准的GeoJSON格式对象&#xff09;saveData(geojson.toGeoJSON())})//从localstroage中读取数据function getData(){if(!localSto…

【HarmonyOS开发】ArkTs编译为SO包的流程记录

1、创建一个Static Library的静态模块 2、编写我们的SO控件 2.1 编译配置 {"apiType": "stageMode","buildOption": {"artifactType": "obfuscation"},"targets": [{"name": "default",&qu…

【FISCO BCOS】二十、多机部署区块链

目录 一、准备环境 二、开始搭建 三、检查节点 1.检查节点进程

Linux:查看端口占用的进程

命令 netstat -tunlp可以从图中看到&#xff0c;端口被那个进程占用&#xff0c;对应进程的pid是多少。

dart语言多线程遇到的问题:Isolate.spawnUri(),在真机调试中无法生成隔离

报错原因 [ERROR:flutter/runtime/dart_vm_initializer.cc(41)] Unhandled Exception: IsolateSpawnException: Unable to spawn isolate: Unsupported isolate URI: 未处理的异常&#xff1a;IsolateSpawnException&#xff1a;无法生成隔离&#xff1a;不支持隔离 URI&…