热门标签 | HotTags
当前位置:  开发笔记 > 编程语言 > 正文

javaZXing生成二维码及条码实例分享

本文分享了javaZXing生成二维码及条码的实例代码,具有很好的参考价值,需要的朋友一起来看下吧

1、jar包:   ZXing-core-3.3.0.jar    http://mvnrepository.com/artifact/com.google.zxing/core

       ZXing-javase-3.3.0.jar   http://mvnrepository.com/artifact/com.google.zxing/javase

BufferedImageLuminanceSource.java

package com.webos.util;
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 = getHeight()) {
   throw new IllegalArgumentException("Requested row is outside the image: " + y);
  }
  int width = getWidth();
  if (row == null || row.length 

QRCodeUtil.java

package com.webos.util;
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.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* @ClassName: QRCodeUtil 
* @Description: 二维码编码
* @author Liuy
* @date 2016年7月9日 下午3:03:24 
* 
*/
public class QRCodeUtil {
 // 设置二维码编码格式
 private static final String CHARSET = "utf-8";
 // 保存的二维码格式
 private static final String FORMAT_NAME = "JPG";
 // 二维码尺寸
 private static final int QRCODE_SIZE = 800;
 // LOGO宽度
 private static final int LOGO_WIDTH = 80;
 // LOGO高度
 private static final int LOGO_HEIGHT = 80;
 /**
  * @Title: createImage
  * @Description: 将二维码内容创建到Image流
  * @param content 二维码内容
  * @param imgPath logo图片地址
  * @param needCompress 是否压缩logo图片大小
  * @return
  * @throws Exception 参数说明
  * @return BufferedImage 返回类型
  * @throws
  */
 private static BufferedImage createImage(String content, String logoPath, 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);
  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  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;
  }
  // 插入LOGO
  Graphics2D 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();
 }
 /**
  * @Title: mkdirs
  * @Description: 创建文件夹
  * @param destPath 文件夹地址
  * @return void 返回类型
  * @throws
  */
 private static boolean mkdirs(String destPath) {
  File file = new File(destPath);
  // 当文件夹不存在时,mkdirs会自动创建多层目录,区别于mkdir.(mkdir如果父目录不存在则会抛出异常)
  if (!file.exists() && !file.isDirectory()) {
   file.mkdirs();
   return true;
  }
  return false;
 }
 /**
  * @Title: encode
  * @Description: 生成二维码
  * @param content 二维码内容
  * @param imgPath logo图片地址
  * @param destPath 目标保存地址
  * @param needCompress 是否压缩logo图片大小
  * @throws Exception 参数说明
  * @return void 返回类型
  * @throws
  */
 private static void encode(String content, String logoPath, String destPath, boolean needCompress) throws Exception {
  BufferedImage image = QRCodeUtil.createImage(content, logoPath, needCompress);
  if (mkdirs(destPath)) {
   String file = new Random().nextInt(99999999) + ".jpg";
   ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + file));
  }
 }
 /**
  * @Title: encode
  * @Description: 生成二维码
  * @param content 二维码内容
  * @param destPath 目标保存地址
  * @throws Exception 参数说明
  * @return void 返回类型
  * @throws
  */
 public static void encode(String content, String destPath) throws Exception {
  QRCodeUtil.encode(content, null, destPath, false);
 }
 /**
  * @Title: encode
  * @Description: 生成二维码
  * @param content 二维码内容
  * @param imgPath logo图片地址
  * @param output 输出流
  * @param needCompress 是否压缩logo图片大小
  * @throws Exception 参数说明
  * @return void 返回类型
  * @throws
  */
 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_NAME, output);
 }
 /**
  * @Title: encode
  * @Description: 生成二维码
  * @param content 二维码内容
  * @param output 输出流
  * @throws Exception 参数说明
  * @return void 返回类型
  * @throws
  */
 public static void encode(String content, OutputStream output) throws Exception {
  QRCodeUtil.encode(content, null, output, false);
 }
 /**
  * @Title: decode
  * @Description: 对二维码解码
  * @param file 文件对象
  * @return 解码后的二维码内容字符串
  * @throws Exception 参数说明
  * @return String 返回类型
  * @throws
  */
 private 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));
  Hashtable hints = new Hashtable();
  hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
  return new MultiFormatReader().decode(bitmap, hints).getText();
 }
 /**
  * @Title: decode
  * @Description: 对二维码解码
  * @param path 文件路径
  * @return
  * @throws Exception 参数说明
  * @return String 返回类型
  * @throws
  */
 public static String decode(String path) throws Exception {
  return QRCodeUtil.decode(new File(path));
 }
}

QRCodeServlet.java

package com.webos.servlet;
import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import com.webos.util.QRCodeUtil;
/*
 * Servlet implementation class QRCodeServlet
 */
@WebServlet("/QRCodeServlet")
public class QRCodeServlet extends HttpServlet {
 private static final long serialVersiOnUID= 1L;
 /*
  * @see HttpServlet#HttpServlet()
  */
 public QRCodeServlet() {
  super();
 }
 /*
  * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
  * response)
  */
 protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  try {
   String text = "http://www.baidu.com?timestamp=" + System.currentTimeMillis();
   QRCodeUtil.encode(text, response.getOutputStream());
  } catch (Exception e) {
   e.printStackTrace();
  }
 }
 /*
  * @see HttpServlet#doPost(HttpServletRequest request, HttpServletResponse
  * response)
  */
 protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
  // TODO Auto-generated method stub
  doGet(request, response);
 }
}

以上就是本文的全部内容,希望本文的内容对大家的学习或者工作能带来一定的帮助,同时也希望多多支持!


推荐阅读
  • 在Docker中,将主机目录挂载到容器中作为volume使用时,常常会遇到文件权限问题。这是因为容器内外的UID不同所导致的。本文介绍了解决这个问题的方法,包括使用gosu和suexec工具以及在Dockerfile中配置volume的权限。通过这些方法,可以避免在使用Docker时出现无写权限的情况。 ... [详细]
  • 云原生边缘计算之KubeEdge简介及功能特点
    本文介绍了云原生边缘计算中的KubeEdge系统,该系统是一个开源系统,用于将容器化应用程序编排功能扩展到Edge的主机。它基于Kubernetes构建,并为网络应用程序提供基础架构支持。同时,KubeEdge具有离线模式、基于Kubernetes的节点、群集、应用程序和设备管理、资源优化等特点。此外,KubeEdge还支持跨平台工作,在私有、公共和混合云中都可以运行。同时,KubeEdge还提供数据管理和数据分析管道引擎的支持。最后,本文还介绍了KubeEdge系统生成证书的方法。 ... [详细]
  • 安装mysqlclient失败解决办法
    本文介绍了在MAC系统中,使用django使用mysql数据库报错的解决办法。通过源码安装mysqlclient或将mysql_config添加到系统环境变量中,可以解决安装mysqlclient失败的问题。同时,还介绍了查看mysql安装路径和使配置文件生效的方法。 ... [详细]
  • Final关键字的含义及用法详解
    本文详细介绍了Java中final关键字的含义和用法。final关键字可以修饰非抽象类、非抽象类成员方法和变量。final类不能被继承,final类中的方法默认是final的。final方法不能被子类的方法覆盖,但可以被继承。final成员变量表示常量,只能被赋值一次,赋值后值不再改变。文章还讨论了final类和final方法的应用场景,以及使用final方法的两个原因:锁定方法防止修改和提高执行效率。 ... [详细]
  • 本文介绍了求解gcdexgcd斐蜀定理的迭代法和递归法,并解释了exgcd的概念和应用。exgcd是指对于不完全为0的非负整数a和b,gcd(a,b)表示a和b的最大公约数,必然存在整数对x和y,使得gcd(a,b)=ax+by。此外,本文还给出了相应的代码示例。 ... [详细]
  • 本文介绍了在Python3中如何使用选择文件对话框的格式打开和保存图片的方法。通过使用tkinter库中的filedialog模块的asksaveasfilename和askopenfilename函数,可以方便地选择要打开或保存的图片文件,并进行相关操作。具体的代码示例和操作步骤也被提供。 ... [详细]
  • EPICS Archiver Appliance存储waveform记录的尝试及资源需求分析
    本文介绍了EPICS Archiver Appliance存储waveform记录的尝试过程,并分析了其所需的资源容量。通过解决错误提示和调整内存大小,成功存储了波形数据。然后,讨论了储存环逐束团信号的意义,以及通过记录多圈的束团信号进行参数分析的可能性。波形数据的存储需求巨大,每天需要近250G,一年需要90T。然而,储存环逐束团信号具有重要意义,可以揭示出每个束团的纵向振荡频率和模式。 ... [详细]
  • Iamtryingtomakeaclassthatwillreadatextfileofnamesintoanarray,thenreturnthatarra ... [详细]
  • 在Android开发中,使用Picasso库可以实现对网络图片的等比例缩放。本文介绍了使用Picasso库进行图片缩放的方法,并提供了具体的代码实现。通过获取图片的宽高,计算目标宽度和高度,并创建新图实现等比例缩放。 ... [详细]
  • 本文介绍了在开发Android新闻App时,搭建本地服务器的步骤。通过使用XAMPP软件,可以一键式搭建起开发环境,包括Apache、MySQL、PHP、PERL。在本地服务器上新建数据库和表,并设置相应的属性。最后,给出了创建new表的SQL语句。这个教程适合初学者参考。 ... [详细]
  • Microsoft Office for Mac最新版本安装教程,亲测可用!
    本文介绍了Microsoft Office for Mac最新版本的安装教程,经过亲测可用。Office工具是办公必备的工具,它为用户和企业设计,可以利用功能强大的Outlook处理电子邮件、日历和通讯录事宜。安装包包括Word、Excel、PPT、OneNote和Outlook。阅读本文可以了解如何下载并安装Office,以及安装过程中的注意事项。安装完毕后,可以正常使用Office中的Word等功能。 ... [详细]
  • 电销机器人作为一种人工智能技术载体,可以帮助企业提升电销效率并节省人工成本。然而,电销机器人市场缺乏统一的市场准入标准,产品品质良莠不齐。创业者在代理或购买电销机器人时应注意谨防用录音冒充真人语音通话以及宣传技术与实际效果不符的情况。选择电销机器人时需要考察公司资质和产品品质,尤其要关注语音识别率。 ... [详细]
  • 这是原文链接:sendingformdata许多情况下,我们使用表单发送数据到服务器。服务器处理数据并返回响应给用户。这看起来很简单,但是 ... [详细]
  • 如何去除Win7快捷方式的箭头
    本文介绍了如何去除Win7快捷方式的箭头的方法,通过生成一个透明的ico图标并将其命名为Empty.ico,将图标复制到windows目录下,并导入注册表,即可去除箭头。这样做可以改善默认快捷方式的外观,提升桌面整洁度。 ... [详细]
  • 向QTextEdit拖放文件的方法及实现步骤
    本文介绍了在使用QTextEdit时如何实现拖放文件的功能,包括相关的方法和实现步骤。通过重写dragEnterEvent和dropEvent函数,并结合QMimeData和QUrl等类,可以轻松实现向QTextEdit拖放文件的功能。详细的代码实现和说明可以参考本文提供的示例代码。 ... [详细]
author-avatar
心诚新城
这个家伙很懒,什么也没留下!
PHP1.CN | 中国最专业的PHP中文社区 | DevBox开发工具箱 | json解析格式化 |PHP资讯 | PHP教程 | 数据库技术 | 服务器技术 | 前端开发技术 | PHP框架 | 开发工具 | 在线工具
Copyright © 1998 - 2020 PHP1.CN. All Rights Reserved | 京公网安备 11010802041100号 | 京ICP备19059560号-4 | PHP1.CN 第一PHP社区 版权所有