【java】google的zxing架包生成二维码和读取二维码【可带文字和logo】
承接RC4生成不重复字符串的需求之后,因为优惠码要方便用户使用的缘故,所以思来想去,觉得还是直接生成二维码给用户直接扫比较实用,也不用用户专门记录冗长的优惠码编号。
========================================================
所以这一章,就先把java生成二维码【可带logo和文字】做一记录,使用google的工具包zxing
========================================================
1.maven依赖
<!-- google提供二维码生成和解析https://mvnrepository.com/artifact/com.google.zxing/core -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.2</version>
</dependency>
2.完整代码
package testExample; import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.HashMap;
import java.util.Map; import javax.imageio.ImageIO; import com.google.zxing.*;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeReader;
import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;
import lombok.experimental.Accessors;
import org.springframework.util.StringUtils; import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; /**
* 二维码工具类
* @author SXD
* @Date 2018.2.1
*
*/
public class QR_Code {
private static int BLACK = 0x000000;
private static int WHITE = 0xFFFFFF; /**
* 内部类,设置二维码相关参数
*/
@Data(staticConstructor = "of")
@NoArgsConstructor
@AllArgsConstructor
@Accessors(chain = true)
public class CodeModel {
/**
* 正文
*/
private String contents;
/**
* 二维码宽度
*/
private int width = 400;
/**
* 二维码高度
*/
private int height = 400;
/**
* 图片格式
*/
private String format = "png";
/**
* 编码方式
*/
private String character_set = "utf-8";
/**
* 字体大小
*/
private int fontSize = 12;
/**
* logo
*/
private File logoFile;
/**
* logo所占二维码比例
*/
private float logoRatio = 0.20f;
/**
* 二维码下文字
*/
private String desc;
private int whiteWidth;//白边的宽度
private int[] bottomStart;//二维码最下边的开始坐标
private int[] bottomEnd;//二维码最下边的结束坐标
} /**
* 1.创建最原始的二维码图片
* @param info
* @return
*/
private BufferedImage createCodeImage(CodeModel info){ String contents = StringUtils.isEmpty(info.getContents()) ? "暂无内容" : info.getContents();//获取正文
int width = info.getWidth();//宽度
int height = info.getHeight();//高度
Map<EncodeHintType, Object> hint = new HashMap<>();
hint.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);//设置二维码的纠错级别【级别分别为M L H Q ,H纠错能力级别最高,约可纠错30%的数据码字】
hint.put(EncodeHintType.CHARACTER_SET, info.getCharacter_set());//设置二维码编码方式【UTF-8】
hint.put(EncodeHintType.MARGIN, 0); MultiFormatWriter writer = new MultiFormatWriter();
BufferedImage img = null;
try {
//构建二维码图片
//QR_CODE 一种矩阵二维码
BitMatrix bm = writer.encode(contents, BarcodeFormat.QR_CODE, width, height, hint);
int[] locationTopLeft = bm.getTopLeftOnBit();
int[] locationBottomRight = bm.getBottomRightOnBit();
info.setBottomStart(new int[]{locationTopLeft[0], locationBottomRight[1]});
info.setBottomEnd(locationBottomRight);
int w = bm.getWidth();
int h = bm.getHeight();
img = new BufferedImage(w, h, BufferedImage.TYPE_INT_RGB);
for(int x=0;x<w;x++){
for(int y=0;y<h;y++){
img.setRGB(x, y, bm.get(x, y) ? BLACK : WHITE);
}
}
} catch (WriterException e) {
e.printStackTrace();
}
return img;
} /**
* 2.为二维码增加logo和二维码下文字
* logo--可以为null
* 文字--可以为null或者空字符串""
* @param info
* @param output
*/
private void dealLogoAndDesc(CodeModel info, OutputStream output){
//获取原始二维码图片
BufferedImage bm = createCodeImage(info);
//获取Logo图片
File logoFile = info.getLogoFile();
int width = bm.getWidth();
int height = bm.getHeight();
Graphics g = bm.getGraphics(); //处理logo
if(logoFile!=null && logoFile.exists()){
try{
BufferedImage logoImg = ImageIO.read(logoFile);
int logoWidth = logoImg.getWidth();
int logoHeight = logoImg.getHeight();
float ratio = info.getLogoRatio();//获取Logo所占二维码比例大小
if(ratio>0){
logoWidth = logoWidth>width*ratio ? (int)(width*ratio) : logoWidth;
logoHeight = logoHeight>height*ratio ? (int)(height*ratio) : logoHeight;
}
int x = (width-logoWidth)/2;
int y = (height-logoHeight)/2;
//根据logo 起始位置 和 宽高 在二维码图片上画出logo
g.drawImage(logoImg, x, y, logoWidth, logoHeight, null);
}catch(Exception e){
e.printStackTrace();
}
} //处理二维码下文字
String desc = info.getDesc();
if(!StringUtils.isEmpty(desc)){
try{
//设置文字字体
int whiteWidth = info.getHeight()-info.getBottomEnd()[1];
Font font = new Font("黑体", Font.BOLD, info.getFontSize());
int fontHeight = g.getFontMetrics(font).getHeight();
//计算需要多少行
int lineNum = 1;
int currentLineLen = 0;
for(int i=0;i<desc.length();i++){
char c = desc.charAt(i);
int charWidth = g.getFontMetrics(font).charWidth(c);
if(currentLineLen+charWidth>width){
lineNum++;
currentLineLen = 0;
continue;
}
currentLineLen += charWidth;
}
int totalFontHeight = fontHeight*lineNum;
int wordTopMargin = 4;
BufferedImage bm1 = new BufferedImage(width, height+totalFontHeight+wordTopMargin-whiteWidth, BufferedImage.TYPE_INT_RGB);
Graphics g1 = bm1.getGraphics();
if(totalFontHeight+wordTopMargin-whiteWidth>0){
g1.setColor(Color.WHITE);
g1.fillRect(0, height, width, totalFontHeight+wordTopMargin-whiteWidth);
}
g1.setColor(new Color(BLACK));
g1.setFont(font);
g1.drawImage(bm, 0, 0, null);
width = info.getBottomEnd()[0]-info.getBottomStart()[0];
height = info.getBottomEnd()[1]+1;
currentLineLen = 0;
int currentLineIndex = 0;
int baseLo = g1.getFontMetrics().getAscent();
for(int i=0;i<desc.length();i++){
String c = desc.substring(i, i+1);
int charWidth = g.getFontMetrics(font).stringWidth(c);
if(currentLineLen+charWidth>width){
currentLineIndex++;
currentLineLen = 0;
g1.drawString(c, currentLineLen + whiteWidth, height+baseLo+fontHeight*(currentLineIndex)+wordTopMargin);
currentLineLen = charWidth;
continue;
}
g1.drawString(c, currentLineLen+whiteWidth, height+baseLo+fontHeight*(currentLineIndex) + wordTopMargin);
currentLineLen += charWidth;
}
g1.dispose();
bm = bm1;
}catch(Exception e){
e.printStackTrace();
}
} try{
ImageIO.write(bm, StringUtils.isEmpty(info.getFormat()) ? info.getFormat() : info.getFormat(), output);
}catch(Exception e){
e.printStackTrace();
}
} /**
* 3.创建 带logo和文字的二维码
* @param info
* @param file
*/
public void createCodeImage(CodeModel info, File file){
File parent = file.getParentFile();
if(!parent.exists())parent.mkdirs();
OutputStream output = null;
try{
output = new BufferedOutputStream(new FileOutputStream(file));
dealLogoAndDesc(info, output);
output.flush();
}catch(Exception e){
e.printStackTrace();
}finally{
try {
output.close();
} catch (IOException e) {
e.printStackTrace();
}
}
} /**
* 3.创建 带logo和文字的二维码
* @param info
* @param filePath
*/
public void createCodeImage(CodeModel info, String filePath){
createCodeImage(info, new File(filePath));
} /**
* 4.创建 带logo和文字的二维码
* @param filePath
*/
public void createCodeImage(String contents,String filePath){
CodeModel codeModel = new CodeModel();
codeModel.setContents(contents);
createCodeImage(codeModel, new File(filePath));
} /**
* 5.读取 二维码 获取二维码中正文
* @param input
* @return
*/
public String decode(InputStream input){
Map<DecodeHintType, Object> hint = new HashMap<DecodeHintType, Object>();
hint.put(DecodeHintType.POSSIBLE_FORMATS, BarcodeFormat.QR_CODE);
String result = "";
try{
BufferedImage img = ImageIO.read(input);
int[] pixels = img.getRGB(0, 0, img.getWidth(), img.getHeight(), null, 0, img.getWidth());
LuminanceSource source = new RGBLuminanceSource(img.getWidth(), img.getHeight(), pixels);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
QRCodeReader reader = new QRCodeReader();
Result r = reader.decode(bitmap, hint);
result = r.getText();
}catch(Exception e){
result="读取错误";
}
return result;
} }
3.测试一下
@Test
public void getUUid(){
String ss = RC4.RC4();
System.out.println(ss); QR_Code code = new QR_Code();
// Code.CodeModel codeModel = code.new CodeModel();
// codeModel.setContents(ss);
// codeModel.setWidth(400);
// codeModel.setHeight(400);
// codeModel.setFontSize(15);
// codeModel.setLogoFile(new File("G:/ACODE/29936672.jpg"));
// codeModel.setDesc("国大金象大药房优惠码"); code.createCodeImage(ss,"G:/ACODE/国大金象大药房.jpg");
}
=======================================================
方法 选取哪个生成都可以 大同小异 大同小异 没有区别
======================================================
最后,如果想封装成jar包供别人调用,参考步骤如下:http://www.cnblogs.com/sxdcgaq8080/p/8399854.html
【java】google的zxing架包生成二维码和读取二维码【可带文字和logo】的更多相关文章
- zxing生成二维码和读取二维码
当然,首先要导入zxing的jar包. 生成二维码代码: package com.imooc.zxing; import java.io.File; import java.nio.file.Path ...
- ZXing生成二维码、读取二维码
使用谷歌的开源包ZXing maven引入如下两个包即可 <dependency> <groupId>com.google.zxing</groupId> & ...
- Java开发所需架包官方下载
1.连接MySQL数据库所需架包点击进入官网下载 2.连接Oracle数据库所需架包点击进入官网下载 3.JUnit测试所需架包点击进入官网下载或者点击进入官网下载 4.Struts所需架包点击进入官 ...
- PHP 二维码解码 (读取二维码)
#zbar wget http://ncu.dl.sourceforge.net/project/zbar/zbar/0.10/zbar-0.10.tar.bz2 yum install gtk2 g ...
- jquery-qrcode 生成和读取二维码
首先要导入jar包(生成二维码的jar和读取二维码的jar) 生成二维码: package com.imooc.qrcode; import java.awt.Color; import java.a ...
- java生成二维码,读取(解析)二维码图片
二维码分为好多种,我们最常用的是qrcode类型的二维码,以下有三种生成方式以及解析方式: 附所需jar包或者js地址 第一种:依赖qrcode.jar import java.awt.Color; ...
- ZXing 生成、读取二维码(带logo)
前言 ZXing,一个支持在图像中解码和生成条形码(如二维码.PDF 417.EAN.UPC.Aztec.Data Matrix.Codabar)的库.ZXing(“zebra crossing”)是 ...
- java生成二维码以及读取案例
今天有时间把二维码这块看了一下,方法有几种,我只是简单的看了一下 google 的 zxing! 很简单的一个,比较适合刚刚学习java的小伙伴哦!也比较适合以前没有接触过和感兴趣的的小伙伴,o ...
- 分享:根据webservice WSDL地址自动生成java调用代码及JAR包
分享:根据webservice WSDL地址自动生成java调用代码及JAR包使用步骤:一.安装java 并配置JAVA_HOME 及 path二.安装ANT 并配置ANT_HOME三.解压WsdlT ...
随机推荐
- Linux学习-Linux 主机上的用户讯息传递
查询使用者: w, who, last, lastlog 如果你想要知道目前已登入在系统上面的用户呢?可以透过 w 或 who 来查询喔!如下范例所示: [root@study ~]# w 01:49 ...
- iframe内容刷新
经常有嵌套的iframe的内容无法及时刷新,需要手动刷新,这时候就需要获取iframe,然后调用对象的reload, document.getElementById(iframe的id).conten ...
- CornerStone使用教程(配置SVN,HTTP及svn简单使用)
1.SVN配置 假设你公司svn地址为:svn://192.168.1.111/svn/ios,用户名:svnserver,密码:123456 1:填写主机地址 2:如果你的主机地址中有端口号,如为1 ...
- jQuery 遍历函数 ,javascript中的each遍历
jQuery 遍历函数 jQuery 遍历函数包括了用于筛选.查找和串联元素的方法. 函数 描述 .add() 将元素添加到匹配元素的集合中. .andSelf() 把堆栈中之前的元素集添加到当前集合 ...
- js中的事件委托和事件代理详解
起因: 1.这是前端面试的经典题型,要去找工作的小伙伴看看还是有帮助的: 2.其实我一直都没弄明白,写这个一是为了备忘,二是给其他的知其然不知其所以然的小伙伴们以参考: 概述: 那什么叫事件委托呢?它 ...
- [整理]菜鸟教程:docker使用笔记
- docker # 查看 docker stats 指令的具体使用方法 - docker stats --help # 运行一个web应用 - docker pull training/webapp ...
- SpringMVC对于跨域访问的支持
原文地址:http://docs.spring.io/spring/docs/5.0.0.RC2/spring-framework-reference/web.html#mvc-introductio ...
- java.net.ConnectException: Connection timed out: no further information
ping IP 地址 检查是否连上 重启虚拟机 检查主机
- iOS学习笔记49-Swift(九)访问控制
一.Swift的访问控制 Swift中的访问控制模型基于模块和源文件这两个概念 模块指的是Framework或App bundle.在Swift中,可以用import关键字引入自己的工程. 源文件指的 ...
- 用-webkit-box-reflect制作倒影
1.只在webkit内核的浏览器上有效果 2.语法: -webkit-box-reflect: <direction> <offset> <mask-box-image& ...