JAVA中生成、解析二维码的方法并不复杂,使用google的zxing包就可以实现。下面的方法包含了生成二维码、在中间附加logo、添加文字功能,并有解析二维码的方法。

一、下载zxing的架包,并导入项目中,如下:

最主要的包都在com.google.zxing.core下。如果是maven项目,maven依赖如下:

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

二、二维码生成,附上代码例子,如下:

 public class TestQRcode {

     private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
private static final int margin = 0;
private static final int LogoPart = 4; /**
* 生成二维码矩阵信息
* @param content 二维码图片内容
* @param width 二维码图片宽度
* @param height 二维码图片高度
*/
public static BitMatrix setBitMatrix(String content, int width, int height){
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); // 指定编码方式,防止中文乱码
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H); // 指定纠错等级
hints.put(EncodeHintType.MARGIN, margin); // 指定二维码四周白色区域大小
BitMatrix bitMatrix = null;
try {
bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, width, height, hints);
} catch (WriterException e) {
e.printStackTrace();
}
return bitMatrix;
} /**
* 将二维码图片输出
* @param matrix 二维码矩阵信息
* @param format 图片格式
* @param outStream 输出流
* @param logoPath logo图片路径
*/
public static void writeToFile(BitMatrix matrix, String format, OutputStream outStream, String logoPath) throws IOException {
BufferedImage image = toBufferedImage(matrix);
// 加入LOGO水印效果
if (StringUtils.isNotBlank(logoPath)) {
image = addLogo(image, logoPath);
}
ImageIO.write(image, format, outStream);
} /**
* 生成二维码图片
* @param matrix 二维码矩阵信息
*/
public static BufferedImage toBufferedImage(BitMatrix matrix) {
int width = matrix.getWidth();
int height = matrix.getHeight();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_3BYTE_BGR);
for (int x = 0; x < width; x++) {
for (int y = 0; y < height; y++) {
image.setRGB(x, y, matrix.get(x, y) ? BLACK : WHITE);
}
}
return image;
} /**
* 在二维码图片中添加logo图片
* @param image 二维码图片
* @param logoPath logo图片路径
*/
public static BufferedImage addLogo(BufferedImage image, String logoPath) throws IOException {
Graphics2D g = image.createGraphics();
BufferedImage logoImage = ImageIO.read(new File(logoPath));
// 计算logo图片大小,可适应长方形图片,根据较短边生成正方形
int width = image.getWidth() < image.getHeight() ? image.getWidth() / LogoPart : image.getHeight() / LogoPart;
int height = width;
// 计算logo图片放置位置
int x = (image.getWidth() - width) / 2;
int y = (image.getHeight() - height) / 2;
// 在二维码图片上绘制logo图片
g.drawImage(logoImage, x, y, width, height, null);
// 绘制logo边框,可选
// g.drawRoundRect(x, y, logoImage.getWidth(), logoImage.getHeight(), 10, 10);
g.setStroke(new BasicStroke(2)); // 画笔粗细
g.setColor(Color.WHITE); // 边框颜色
g.drawRect(x, y, width, height); // 矩形边框
logoImage.flush();
g.dispose();
return image;
} /**
* 为图片添加文字
* @param pressText 文字
* @param newImage 带文字的图片
* @param targetImage 需要添加文字的图片
* @param fontStyle 字体风格
* @param color 字体颜色
* @param fontSize 字体大小
* @param width 图片宽度
* @param height 图片高度
*/
public static void pressText(String pressText, String newImage, String targetImage, int fontStyle, Color color, int fontSize, int width, int height) {
// 计算文字开始的位置
// x开始的位置:(图片宽度-字体大小*字的个数)/2
int startX = (width-(fontSize*pressText.length()))/2;
// y开始的位置:图片高度-(图片高度-图片宽度)/2
int startY = height-(height-width)/2 + fontSize;
try {
File file = new File(targetImage);
BufferedImage src = ImageIO.read(file);
int imageW = src.getWidth(null);
int imageH = src.getHeight(null);
BufferedImage image = new BufferedImage(imageW, imageH, BufferedImage.TYPE_INT_RGB);
Graphics g = image.createGraphics();
g.drawImage(src, 0, 0, imageW, imageH, null);
g.setColor(color);
g.setFont(new Font(null, fontStyle, fontSize));
g.drawString(pressText, startX, startY);
g.dispose();
FileOutputStream out = new FileOutputStream(newImage);
ImageIO.write(image, "png", out);
out.close();
} catch (Exception e) {
e.printStackTrace();
}
} public static void main(String[] args) {
String content = "http://www.baidu.com";
String logoPath = "C:/logo.png";
String format = "jpg";
int width = 180;
int height = 220;
BitMatrix bitMatrix = setBitMatrix(content, width, height);
// 可通过输出流输出到页面,也可直接保存到文件
OutputStream outStream = null;
String path = "c:/qr"+new Date().getTime()+".png";
try {
outStream = new FileOutputStream(new File(path));
writeToFile(bitMatrix, format, outStream, logoPath);
outStream.close();
} catch (Exception e) {
e.printStackTrace();
}
// 添加文字效果
int fontSize = 12; // 字体大小
int fontStyle = 1; // 字体风格
String text = "测试二维码";
String withTextPath = "c:/text"+new Date().getTime()+".png";
pressText(text, withTextPath, path, fontStyle, Color.BLUE, fontSize, width, height);
}
}

三、生成效果如下:

  代码注释比较详细,就不多解释啦,大家可以根据自己的需求进行调整。

PS:

1、如果想生成带文字的二维码,记得要用长方形图片,为文字预留空间。

2、要生成带logo的二维码要注意遮挡率的问题,setBitMatrix()方法中ErrorCorrectionLevel.H这个纠错等级参数决定了二维码可被遮挡率。对应如下:

L水平 7%的字码可被修正
M水平 15%的字码可被修正
Q水平 25%的字码可被修正
H水平 30%的字码可被修正

四、二维码解析,附上代码例子,如下:

     /**
* 解析二维码图片
* @param filePath 图片路径
*/
public static String decodeQR(String filePath) {
if ("".equalsIgnoreCase(filePath) && filePath.length() == 0) {
return "二维码图片不存在!";
}
String content = "";
EnumMap<DecodeHintType, Object> hints = new EnumMap<DecodeHintType, Object>(DecodeHintType.class);
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8"); // 指定编码方式,防止中文乱码
try {
BufferedImage image = ImageIO.read(new FileInputStream(filePath));
LuminanceSource source = new BufferedImageLuminanceSource(image);
Binarizer binarizer = new HybridBinarizer(source);
BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
MultiFormatReader reader = new MultiFormatReader();
Result result = reader.decode(binaryBitmap, hints);
content = result.getText();
} catch (Exception e) {
e.printStackTrace();
}
return content;
}

  可以从二维码图片中解析出具体的内容。

JAVA中生成、解析二维码图片的方法的更多相关文章

  1. Java使用ZXing生成/解析二维码图片

    ZXing是一种开源的多格式1D/2D条形码图像处理库,在Java中的实现.重点是在手机上使用内置摄像头来扫描和解码设备上的条码,而不与服务器通信.然而,该项目也可以用于对桌面和服务器上的条形码进行编 ...

  2. ZXing 生成、解析二维码图片的小示例

    概述 ZXing 是一个开源 Java 类库用于解析多种格式的 1D/2D 条形码.目标是能够对QR编码.Data Matrix.UPC的1D条形码进行解码. 其提供了多种平台下的客户端包括:J2ME ...

  3. qrcode.js的识别解析二维码图片和生成二维码图片

    qrcode只通过前端就能生成二维码和解析二维码图片, 首先要引入文件qrcode.js,下载地址为:http://static.runoob.com/download/qrcodejs-04f46c ...

  4. 使用zxing生成解析二维码

    1. 前言 随着移动互联网的发展,我们经常在火车票.汽车票.快餐店.电影院.团购网站以及移动支付等各个场景下见到二维码的应用,可见二维码以经渗透到人们生活的各个方面.条码.二维码以及RFID被人们应用 ...

  5. 用CIFilter生成QRCode二维码图片

    用CIFilter生成QRCode二维码图片 CIFilter不仅仅可以用来做滤镜,它还可以用来生成二维码. CIFilterEffect.h + CIFilterEffect.m // // CIF ...

  6. java生成/解析二维码

    package a; import java.awt.BasicStroke; import java.awt.Graphics; import java.awt.Graphics2D; import ...

  7. JAVA生成解析二维码

    package com.mohe.twocode; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.B ...

  8. pbfunc外部函数扩展应用-直接在Datawindow中生成QR二维码,非图片方式

    利用pbfunc外部函数在Datawindow中直接生成QR二维码,非图片方式.需要注意以下面几点: Datawindow的DataObject的单位必须为像素(Pixels). Datawindow ...

  9. .net如何解析二维码图片

    二维码现在越来越流行,可以使用手机上或其它移动终端上的二维码扫描器软件对着二维码一扫,就可以得到相关信息.在互联网站上,可以找到很多二维码的工具,甚至还有不少在线生成.解析二维码的网站.在业务系统当中 ...

随机推荐

  1. linux下安装ffmpeg

    1. 首先安装系统编译环境  yum install -y automake autoconf libtool gcc gcc-c++  #CentOS 2. 编译所需源码包 #yasm:汇编器,新版 ...

  2. Django 1.10中文文档-第一个应用Part1-请求与响应

    在本教程中,我们将引导您完成一个投票应用程序的创建,它包含下面两部分: 一个可以进行投票和查看结果的公开站点: 一个可以进行增删改查的后台admin管理界面: 我们假设你已经安装了Django.您可以 ...

  3. js压缩文件读取处理

    1.引入必须依赖库jszip+jsutils=>>>建议使用以下版本,其他版本的jszip会报错 <!--zip文件读取--> <script src=" ...

  4. iptables网络安全服务详细使用

    iptables防火墙概念说明 开源的基于数据包过滤的网络安全策略控制工具. centos6.9  --- 默认防火墙工具软件iptables centos7    --- 默认防火墙工具软件fire ...

  5. Beyond Globally Optimal: Focused Learning

    这里对WWW 2017文章<Beyond Globally Optimal: Focused Learning for Improved Recommendations>进行一个简单的分析 ...

  6. SQL server学习(二)表结构操作、SQL函数、高级查询

    数据库查询的基本格式为: select ----输出(显示)你要查询出来的值 from -----查询的依据 where -----筛选条件(对依据(数据库中存在的表)) group by ----- ...

  7. Redux 介绍

    本文主要是对 Redux 官方文档 的梳理以及自身对 Redux 的理解. 单页面应用的痛点 对于复杂的单页面应用,状态(state)管理非常重要.state 可能包括:服务端的响应数据.本地对响应数 ...

  8. HDU-5421Victor and String

    题目:http://acm.hdu.edu.cn/showproblem.php?pid=5421 因为要在前面插字符,所以维护一个前缀链和后缀链,在同一棵回文树上搞,如果有某个最长回文后缀(或前缀) ...

  9. Exponentiation(java 大实数)

    http://acm.hdu.edu.cn/showproblem.php?pid=1063 Exponentiation Time Limit: 2000/500 MS (Java/Others)  ...

  10. Ubuntu搭建Gitlab服务器

    想到Gitlab就必定会想到SVN,因为两者都是代码管理系统,作为开发人员来说,用习惯了SVN的图形化界面和SVN代码更新和提交的方式, 可能就会觉得使用git会比较麻烦,其实不然git使用起来非常方 ...