JAVA生成二维码QRcode

  • 1 : 配置集成
    • 1.1、配置maven
    • 1.2、配置文件
    • 1.3、logo文件
  • 2 : 代码集成
    • 2.1、加载配置文件
    • 2.2、工具类
    • 2.3、测试类
  • 3 : 测试结果
    • 3.1、生成二维码
    • 3.2、扫描结果
    • 3.3、资源

1 : 配置集成

1.1、配置maven

pom文件中添加一下配置

<!-- QR code -->
<dependency><groupId>com.google.zxing</groupId><artifactId>core</artifactId><version>3.3.0</version>
</dependency>

1.2、配置文件

新建配置文件 qr-image-config.properties
放置路径 /app/qrcode/config

#是否使用默认验证码:true:使用默认验证码;false:不使用默认验证码
useDefaultCode = false
#默认验证码
defaultCode = 123456
#二维码需要嵌入的图片地址,不设置则不嵌入
signImagePath = /app/qrcode/logo/logo.png
#二维码上传至服务器的地址
imageUploadPath = /app/qrcode/generate/
#二维码生成的随机数位数
codeDigit = 6
#二维码生成的随机数类型:1:数字;2:大写字母;3:小写字母;4:数字+大写字母;5:数字+小写字母;6:数字+大小写字母
codeType = 6
#二维码生成的图片类型
fileType = .jpg
#二维码有效期,单位秒
validityTime = 60

1.3、logo文件

可有可无,不需要也可以不用
logo图片 logo.png
放置路径 /app/qrcode/logo

2 : 代码集成

2.1、加载配置文件

新建 QrImagePathConfig.java

package com.qrcode;import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.support.EncodedResource;
import org.springframework.core.io.support.PropertiesLoaderUtils;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.util.Properties;/*** 获取二维码图片存取路径*/
public class QrImagePathConfig {private Log log = LogFactory.getLog(this.getClass());private static final QrImagePathConfig QR_CONFIG = new QrImagePathConfig();private static final String CONFIG_FILE_NAME = "/app/qrcode/config/qr-image-config.properties";private String useDefaultCode ;//是否使用默认验证码:true:使用默认验证码;false:不使用默认验证码private String defaultCode ;//默认验证码private String signImagePath ;//二维码需要嵌入的图片地址private String imageUploadPath ;//二维码上传至服务器的地址private String codeDigit ;//二维码生成的随机数位数private String codeType ;//二维码生成的随机数类型:1:数字;2:大写字母;3:小写字母;4:数字+大写字母;5:数字+小写字母;6:数字+大小写字母private String fileType ;//二维码生成的图片类型private String validityTime ;//二维码有效期,单位秒public String getUseDefaultCode() {return useDefaultCode;}public void setUseDefaultCode(String useDefaultCode) {this.useDefaultCode = useDefaultCode;}public String getDefaultCode() {return defaultCode;}public void setDefaultCode(String defaultCode) {this.defaultCode = defaultCode;}public String getSignImagePath() {return signImagePath;}public void setSignImagePath(String signImagePath) {this.signImagePath = signImagePath;}public String getImageUploadPath() {return imageUploadPath;}public void setImageUploadPath(String imageUploadPath) {this.imageUploadPath = imageUploadPath;}public String getCodeDigit() {return codeDigit;}public void setCodeDigit(String codeDigit) {this.codeDigit = codeDigit;}public String getCodeType() {return codeType;}public void setCodeType(String codeType) {this.codeType = codeType;}public String getFileType() {return fileType;}public void setFileType(String fileType) {this.fileType = fileType;}public String getValidityTime() {return validityTime;}public void setValidityTime(String validityTime) {this.validityTime = validityTime;}public static QrImagePathConfig getQrConfig() {return QR_CONFIG;}static{QR_CONFIG.loadProperties();}private void loadProperties(){try {Properties properties = null;if(CONFIG_FILE_NAME.startsWith("/")){properties = new Properties();properties.load(new FileReader(new File(CONFIG_FILE_NAME)));} else {properties = PropertiesLoaderUtils.loadProperties(new EncodedResource(new ClassPathResource(CONFIG_FILE_NAME),"UTF-8"));}log.info("加载文件" + CONFIG_FILE_NAME + "成功!");String useDefaultCode = properties.getProperty("useDefaultCode");String defaultCode = properties.getProperty("defaultCode");String signImagePath = properties.getProperty("signImagePath");String imageUploadPath = properties.getProperty("imageUploadPath");String codeDigit = properties.getProperty("codeDigit");String codeType = properties.getProperty("codeType");String fileType = properties.getProperty("fileType");String validityTime = properties.getProperty("validityTime");log.info("useDefaultCode:"+useDefaultCode+"defaultCode:"+defaultCode+"signImagePath:"+signImagePath+",imageUploadPath:"+imageUploadPath+",codeDigit:"+codeDigit+",codeType:"+codeType+",fileType:"+fileType+",validityTime:"+validityTime);QR_CONFIG.useDefaultCode = useDefaultCode;QR_CONFIG.defaultCode = defaultCode;QR_CONFIG.signImagePath = signImagePath;QR_CONFIG.imageUploadPath = imageUploadPath;QR_CONFIG.codeDigit = codeDigit;QR_CONFIG.codeType = codeType;QR_CONFIG.fileType = fileType;QR_CONFIG.validityTime = validityTime;} catch (IOException e) {log.warn("加载配置文件:" + CONFIG_FILE_NAME + " 失败",e);}}
}

2.2、工具类

新建BufferedImageLuminanceSource.java

package com.qrcode;import java.awt.Graphics2D;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import com.google.zxing.LuminanceSource;public class BufferedImageLuminanceSource extends LuminanceSource {private final BufferedImage image;private final int left;private final int top;public BufferedImageLuminanceSource(BufferedImage image) {this(image, 0, 0, image.getWidth(), image.getHeight());}public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {super(width, height);int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();if (left + width > sourceWidth || top + height > sourceHeight) {throw new IllegalArgumentException("Crop rectangle does not fit within image data.");}for (int y = top; y < top + height; y++) {for (int x = left; x < left + width; x++) {if ((image.getRGB(x, y) & 0xFF000000) == 0) {image.setRGB(x, y, 0xFFFFFFFF); // = white}}}this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);this.image.getGraphics().drawImage(image, 0, 0, null);this.left = left;this.top = top;}public byte[] getRow(int y, byte[] row) {if (y < 0 || y >= getHeight()) {throw new IllegalArgumentException("Requested row is outside the image: " + y);}int width = getWidth();if (row == null || row.length < width) {row = new byte[width];}image.getRaster().getDataElements(left, top + y, width, 1, row);return row;}public byte[] getMatrix() {int width = getWidth();int height = getHeight();int area = width * height;byte[] matrix = new byte[area];image.getRaster().getDataElements(left, top, width, height, matrix);return matrix;}public boolean isCropSupported() {return true;}public LuminanceSource crop(int left, int top, int width, int height) {return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);}public boolean isRotateSupported() {return true;}public LuminanceSource rotateCounterClockwise() {int sourceWidth = image.getWidth();int sourceHeight = image.getHeight();AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);Graphics2D g = rotatedImage.createGraphics();g.drawImage(image, transform, null);g.dispose();int width = getWidth();return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);}
}

新建 QRCodeUtil.java

package com.qrcode;import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.DecodeHintType;
import com.google.zxing.EncodeHintType;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;public class QRCodeUtil {private static final String CHARSET = "utf-8";private static final String FORMAT_NAME = "JPG";// 二维码尺寸private static final int QR_CODE_SIZE = 300;// LOGO宽度private static final int WIDTH = 60;// LOGO高度private static final int HEIGHT = 60;private static BufferedImage createImage(String content, String imgPath, boolean needCompress) throws Exception {Hashtable hints = new Hashtable();hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//设置编码字符集hints.put(EncodeHintType.CHARACTER_SET, CHARSET);hints.put(EncodeHintType.MARGIN, 1);//1、生成二维码BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QR_CODE_SIZE, QR_CODE_SIZE, hints);//2、获取二维码宽高int width = bitMatrix.getWidth();int height = bitMatrix.getHeight();//3、将二维码放入缓冲流BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);for (int x = 0; x < width; x++) {for (int y = 0; y < height; y++) {//4、循环将二维码内容定入图片image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);}}if (imgPath == null || "".equals(imgPath)) {return image;}// 插入图片QRCodeUtil.insertImage(image, imgPath, needCompress);return image;}private static void insertImage(BufferedImage source, String imgPath, boolean needCompress) throws Exception {File file = new File(imgPath);if (!file.exists()) {System.err.println("" + imgPath + "   该文件不存在!");return;}Image src = ImageIO.read(new File(imgPath));int width = src.getWidth(null);int height = src.getHeight(null);if (needCompress) { // 压缩LOGOif (width > WIDTH) {width = WIDTH;}if (height > HEIGHT) {height = 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 = (QR_CODE_SIZE - width) / 2;int y = (QR_CODE_SIZE - height) / 2;
//        graph.setColor(Color.BLUE);//设定嵌入的图像边框颜色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();}public static void encode(String content, String imgPath, String destPath, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);mkdirs(destPath);// String file = new Random().nextInt(99999999)+".jpg";// ImageIO.write(image, FORMAT_NAME, new File(destPath+"/"+file));ImageIO.write(image, FORMAT_NAME, new File(destPath));}public static BufferedImage encode(String content, String imgPath, boolean needCompress) throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);return image;}public static void mkdirs(String destPath) {File file = new File(destPath);// 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)if (!file.exists() && !file.isDirectory()) {file.mkdirs();}}public static void encode(String content, String imgPath, String destPath) throws Exception {QRCodeUtil.encode(content, imgPath, destPath, false);}// 被注释的方法/** public static void encode(String content, String destPath, boolean* needCompress) throws Exception { QRCodeUtil.encode(content, null, destPath,* needCompress); }*/public static void encode(String content, String destPath) throws Exception {QRCodeUtil.encode(content, null, destPath, false);}public static void encode(String content, String imgPath, OutputStream output, boolean needCompress)throws Exception {BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);ImageIO.write(image, FORMAT_NAME, output);}public static void encode(String content, OutputStream output) throws Exception {QRCodeUtil.encode(content, null, output, false);}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 hints = new Hashtable();hints.put(DecodeHintType.CHARACTER_SET, CHARSET);result = new MultiFormatReader().decode(bitmap, hints);String resultStr = result.getText();return resultStr;}public static String decode(String path) throws Exception {return QRCodeUtil.decode(new File(path));}
}

2.3、测试类

新建 QrCodeTest.java

package com.qrcode;import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import java.util.UUID;public class QrCodeTest {public static void main(String[] args) throws Exception {//text存放在二维码中的内容String num = "";if("true".equals(QrImagePathConfig.getQrConfig().getUseDefaultCode())){num = QrImagePathConfig.getQrConfig().getDefaultCode();} else {num = getRandomCodeByDigitAndType(Integer.valueOf(QrImagePathConfig.getQrConfig().getCodeDigit()),Integer.valueOf(QrImagePathConfig.getQrConfig().getCodeType()));}String text = "二维码测试,验证码为:\n" + "*********************\n" + "****** "+ num +" ******\n" + "*********************";//imgPath嵌入二维码的图片路径
//        String imgPath = "E:\\app\\qrcode\\config\\logo.png";
//        String imgPath = "/app/qrcode/config/logo.png";String imgPath = QrImagePathConfig.getQrConfig().getSignImagePath();//destPath生成的二维码的路径及名称String fileName = UUID.randomUUID().toString().replaceAll("-", "").substring(0,10);String destPath = QrImagePathConfig.getQrConfig().getImageUploadPath() + fileName + QrImagePathConfig.getQrConfig().getFileType();//生成二维码//text:编码到二维码中的内容;imgPath:要嵌入二维码的图片路径,如果不写或者为null则生成一个没有嵌入图片的纯净的二维码//destPath:生成的二维码的存放路径;true:表示将嵌入二维码的图片进行压缩,如果为“false”则表示不压缩.QRCodeUtil.encode(text, imgPath, destPath, true);//解析二维码//destPath:将要解析的二维码的存放路径;该方法返回值为String类型,即返回解析出的文字或者数字等.String str = QRCodeUtil.decode(destPath);//打印出解析出的内容System.out.println(str);//二维码存的信息越多,二维码图片也就越复杂,容错率也就越低,识别率也越低,并且二维码能存的内容大小也是有限的(大概500个汉字左右)}/*** 根据位数和类型获取验证码* @param codeDigit  随机数位数* @param codeType  随机数类型:1:数字;2:大写字母;3:小写字母;4:数字+大写字母;5:数字+小写字母;6:数字+大小写字母* @return*/public static String getRandomCodeByDigitAndType(Integer codeDigit,Integer codeType) {String string = "";String numStr = "0123456789";String lowerCaseLetter = "abcdefghijklmnopqrstuvwxyz";String upperCaseLetter = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";switch (codeType){case 1:string = numStr;break;case 2:string = upperCaseLetter;break;case 3:string = lowerCaseLetter;break;case 4:string = numStr + upperCaseLetter;break;case 5:string = numStr + lowerCaseLetter;break;case 6:string = numStr + lowerCaseLetter + upperCaseLetter;break;}string = getStringForDisorderSorting(string);//将字符串的顺序打乱StringBuilder stringBuilder = new StringBuilder();//声明一个StringBuffer对象保存验证码for (int i = 0; i < codeDigit; i++) {Random random = new Random();//创建随机数生成器int index = random.nextInt(string.length());//返回[0,string.length)范围的int值,保存下标char charAt = string.charAt(index);//charAt(),返回指定索引处的char值stringBuilder.append(charAt);//将charAt字符串追加到此序列}return stringBuilder.toString();//返回字符串}/*** 随机打乱一个字符串的排序方式* @param string* @return*/private static String getStringForDisorderSorting(String string) {char[] chars = string.toCharArray();List<Character> characterList = new ArrayList<Character>();for(char ch:chars){characterList.add(ch);}Collections.shuffle(characterList);StringBuilder stringBuilder = new StringBuilder();for(Character character:characterList){stringBuilder.append(character);}return stringBuilder.toString();}/*** 根据位数获取数字验证码* @param codeDigit* @return*/private static String getRandomNum(Integer codeDigit){StringBuilder stringBuilder=new StringBuilder();Random random = new Random();for (int i = 0; i < codeDigit; i++) {stringBuilder.append(random.nextInt(10));}return stringBuilder.toString();}
}

3 : 测试结果

3.1、生成二维码

在路径 /app/qrcode/generate

3.2、扫描结果

3.3、资源

CSDN下载链接:https://download.csdn.net/download/qq_38254635/87351537
百度云下载链接:https://pan.baidu.com/s/1zBaTmv2WgG8Ihx-HIEdoow?pwd=v7mc
提取码: v7mc

有什么不对的还望指正,书写不易,觉得有帮助就点个赞吧!

JAVA生成二维码QRcode相关推荐

  1. java 生成二维码 QRCode、zxing 两种方式

    版权声明:本文为 testcs_dn(微wx笑) 原创文章,非商用自由转载-保持署名-注明出处,谢谢. https://blog.csdn.net/testcs_dn/article/details/ ...

  2. Java 生成二维码 Qrcode

    Java生成二维码图片 使用Qrcode.jar jar包点击 免费下载 可直接使用 /*** 生成二维码* @param content 二维码内容 只能存储字符串(如需打开文件,把文件路径存入即可 ...

  3. Java实现二维码QRCode的编码和解码

    涉及到的一些主要类库 编码lib:Qrcode_swetake.jar         (官网介绍-- http://www.swetake.com/qr/index-e.html)          ...

  4. java生成二维码打印到浏览器

    java生成二维码打印到浏览器 解决方法: pom.xml的依赖两个jar包: <!-- https://mvnrepository.com/artifact/com.google.zxing/ ...

  5. Java生成二维码带LOGO底部标题竖版字体

    前言 Java后端生成二维码 底部 侧面带有标题,可调节字号 参考文章 使用Java生成二维码图片(亲测) Reborn_YY使用Java生成二维码图片 图标素材库 Java后台生成图片,前台实现图片 ...

  6. java生成二维码,并在前端展示。

    java生成二维码,并在前端展示,扫码实现下载功能. 后端生成二维码以流的形式 前端接收二维码并展示 后端生成二维码以流的形式 这是以流的形式展示二维码.当然也可以以文件的格式,文件格式就是Path ...

  7. java生成二维码(链接生成二维码)

    Java二维码如何生成? awt.image.BufferedImage; import java.io.File; import javax.imageio.ImageIO; import com. ...

  8. java生成二维码扫描跳转到指定的路径URL

    java生成二维码扫描跳转到指定的路径URL 导入依赖 <dependency><groupId>com.google.zxing</groupId><art ...

  9. Java 生成二维码 zxing生成二维码 条形码 服务端生成二维码 Java生成条形码

    Java 生成二维码 zxing生成二维码 条形码 服务端生成二维码 Java生成条形码 一.关于ZXing 1.ZXing是谷歌开源的支持二维码.条形码 等图形的生成类库:支持生成.和解码功能. G ...

最新文章

  1. 2019 ACM - ICPC 全国邀请赛(南昌) 题解(9 / 12)
  2. SqlSessionFactoryBuilder、SqlSessionFactory、SqlSession作用域(Scope)和生命周期
  3. 第十届蓝桥杯大赛青少年创意编程C++组省赛 第2题 小猫吃鱼
  4. 编辑器扩展_开发者必备,可扩展编辑器tui.editor和TOAST UI组件家族
  5. 递归下降分析法的基本思想。_八大算法思想总结提高
  6. bme280中文技术手册_Rhino 6 中文训练手册发布
  7. 引用 使用Eclipse生成Java Doc
  8. GameMap地图初始化
  9. java代码反编译 工具下载及注意事项 xjad下载
  10. ad建集成库_手把手教你创建自己的Altium Designer集成元件库
  11. 电脑时间显示到秒 设置电脑显示时间为秒
  12. 关于node debug myscript.js的问题
  13. BZOJ 1127 [POI2008]KUP 最大子矩阵
  14. 第008篇:ArcGIS中点对落入多边形的位置关系(相邻/相离)的判定
  15. (学习笔记)OrCAD进行DRC时报错以及解决办法
  16. 华人工程师盗窃苹果商业机密,后果有多严重?
  17. 土地资源管理就业怎么这么难_土地资源管理就业前景怎么样
  18. 多电脑共享键鼠——sharemouse 2021-08-21
  19. 拉格朗日函数相关推导
  20. AutoCAD炸开轴号后文字会发生改变

热门文章

  1. 2021年最新的服务器系统,微软为2021年下半年准备Windows Server LTSC的下一个版本
  2. LINUX命令后面常见的/dev/null 解释
  3. 计算机处理器ghz,ghz指的是计算机的
  4. 2020年美赛回顾与总结
  5. oracle 数据泵impdp导入dmp文件时更改用户及表空间方法
  6. 多云环境下部署 k3s 集群
  7. FCKeditor在.NET的使用方法
  8. 前端实现模糊搜索功能
  9. 二:Hexo 页面编写
  10. 根目录index.php-wp-blog-header.php-wp-load.php-wp-config.php