本工具类基于Google二维码框架zxing3.1.0实现。

1. pom.xml中依赖包设置

<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>

2. 二维码工具类

import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.OutputStream;
import java.util.Hashtable;
import java.util.Random;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.client.j2se.BufferedImageLuminanceSource;
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 = "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.baidu.com";//不含Logo//QRCodeUtil.encode(text, null, "e:\\", true);//含Logo,不指定二维码图片名//QRCodeUtil.encode(text, "e:\\csdn.jpg", "e:\\", true);//含Logo,指定二维码图片名QRCodeUtil.encode(text, "e:\\csdn.jpg", "e:\\", "qrcode", true);}
}

参考资料:
1. http://blog.csdn.net/mmm333zzz/article/details/17259513
2. http://kesun-shy.iteye.com/blog/2154169

Java二维码工具类(使用zxing实现,可支持logo)相关推荐

  1. Java二维码工具类(超详细注释)

    二维码工具类 准备工作: pom.xml 引入依赖 <!-- 二维码 --> <dependency><groupId>com.google.zxing</g ...

  2. java将链接生成二维码工具类

    一.添加依赖 <!-- 生成二维码--><dependency><groupId>com.google.zxing</groupId><artif ...

  3. com.google.zxing 二维码工具类

    com.google.zxing 二维码工具类 pom 工具类 使用 pom <dependency><groupId>com.google.zxing</groupId ...

  4. Java生成和解析二维码工具类(简单经典)

    Java生成和解析二维码工具类 开箱即用,简单不废话. pom.xml引入依赖 <!-- https://mvnrepository.com/artifact/com.google.zxing/ ...

  5. java生成二维码工具类

    1,先引入谷歌的插件zxing的maven坐标 <!-- 二维码 --><dependency><groupId>com.google.zxing</grou ...

  6. 分享一个Java生成二维码工具类

    分享一个Java生成二维码工具类 直接上代码: 1.CodeUtil.class package top.lrshuai.blog.util;import java.awt.BasicStroke; ...

  7. 2021-08-26(条形码,二维码工具类生成)

    公司需要对商品的条码值生成对应的条形码,目前市面上的有的条码库分为: JBarcode,zxing jbarcode这个包在maven的官方仓库找不到,所以需要自己添加到本地仓库然后编写pom文件就可 ...

  8. Android-生成二维码工具类

    目录 二维码生成工具类 二维码生成工具类 /*** 生成条形码和二维码的工具*/ public class ZXingUtils {/*** 生成二维码 要转换的地址或字符串,可以是中文** @par ...

  9. Android 生成二维码工具类

    /*** 生成条形码和二维码的工具*/ public class ZXingUtils {/*** 生成二维码 要转换的地址或字符串,可以是中文** @param url* @param width* ...

最新文章

  1. 【收藏】23个机器学习最佳入门项目(附源代码)
  2. 常用 Linux 命令
  3. 微服务框架 Go-Micro 集成 Nacos 实战之服务注册与发现
  4. java中的深度克隆浅克隆_了解Java中的可克隆接口
  5. 编写jmeter测试用例_Jmeter | 实现接口自动化设计说明
  6. 记录远程桌面登录者的IP和MAC
  7. java模拟摇摆小球程序代码_Android实现左右摆动的球体动画效果
  8. 发牌一周年 国内5G发展如何?
  9. 【Spring Boot + Vue 实际案例】
  10. Debian - RAID5搭建(热备)
  11. U-BOOT 编译过程
  12. matlab fftshift函数,matlab fft fftshift--【转帖】
  13. abaqus中python怎么建立参考点_怎么在abaqus中选定中心为参考点
  14. android横竖屏切换布局闪退,D10上旋转屏幕闪退怎么回事
  15. 终极玩转Power BI中Drill-down Choropleth 地图
  16. STM32F7 DSP库 FFT过程记录
  17. deepin - PS CS6 弹出试用结束(解决方案)
  18. 2023拼多多店铺分类id
  19. (干货)微信小程序项目——泡泡云音乐day2
  20. 零售-商品/门店管理系统 | 进销存系统

热门文章

  1. GPRS模块与STM32的数据传输
  2. 2018最新CATIA飞机协同设计制造工作站配置方案
  3. “很抱歉,出现错误,word不能启动”超简单解决方法
  4. C++——new和delete操作符
  5. C++STL标准库学习笔记(一)sort
  6. DevOps 工程师面试问题(持续更新)
  7. C++语言程序设计——知识点复盘(第四章 类与对象)
  8. ceph报 daemons have recently crashed
  9. CF1428 E. Carrots for Rabbits 贪心+优先队列
  10. SAP中重订货点Reorder Point原理分析及测试