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. unity3d 打包个人记录

    证书问题Android:CreateCer.bat ztmyseabed 路径:tool/Build/Windows/Android下iOS:MacCer文件夹如何上传ipa:修改版本号version ...

  2. 使用Git命令把本地项目上传到github上托管

    (1)在github上,新建一个仓库 (2)打开git-bash,进入项目目录下 (3)git init (4)git add . (5)git status (6)git commit -m &qu ...

  3. 【sunday算法】玄学字符串匹配

    和KMP相似,用于字符串的匹配,貌似平均复杂度比KMP快,也比KMP更好理解. 大概意思是: 如果串b被串a包含,那么串a此时与串b匹配的部分一定一样 所以如果从开头开始匹配到不同处时,在a串找中此时 ...

  4. JavaScript图片库(简单的应用案例)

    这个图片库小例子的效果如图所示,点击网页上某个图片链接时你将看到两种效果:占位符图片呗替换成这个链接所指向的图片,同时描述性文字也被替换为这个链接的title属性值.     利用一个简单的图片库应用 ...

  5. 高通secury boot过程

    整理内容网盘地址: 链接:https://share.weiyun.com/79c3920b4f2097d93b719b3149a7f3f9 (密码:4jm9cx) 相关内容网站: http://bl ...

  6. 关于java解析xml文件出现的问题

    DOM解析xml文件 问题1:导入javax.xml.parsers.DocumentBuilderFactory出现问题,如图: 解决办法是:由于创建工程时有个默认的jre,重新创建工程改掉就解决了 ...

  7. 【个人笔记】《知了堂》ajax的get及post请求

    ajax 执行步骤 // 步骤 设置事件 调用函数 创建一个XHR对象 打开ajax通道,链接服务器,配置请求信息和参数 发送数据 设置回调函数 服务器接受请求,处理请求,查询数据库,响应 及 返回数 ...

  8. windows sevser 2012搭建网站

    1,首先去服务器配置,从哪里下载iis8.0和asp.net和net.xx和web服务,iis控制,ftp等等服务根据自己的需求安装 安装好后把默认的网站删除掉.或者新建一个网站,把服务端口改为其他端 ...

  9. 给“file”类型的input框赋值的问题

    开发"新闻编辑"功能时,会遇到给"file"类型的input框赋值的问题,用来展示之前上传的文件,但由于file类型的input框受到安全限制,所以不能被赋值, ...

  10. UEP-时间

    时间戳转化为Date(or String) SimpleDateFormat format = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss" ...