java生成二维码,读取(解析)二维码图片
二维码分为好多种,我们最常用的是qrcode类型的二维码,以下有三种生成方式以及解析方式:
附所需jar包或者js地址
第一种:依赖qrcode.jar
-
import java.awt.Color;
-
import java.awt.Graphics2D;
-
import java.awt.image.BufferedImage;
-
import java.io.File;
-
import java.io.UnsupportedEncodingException;
-
-
import javax.imageio.ImageIO;
-
-
import com.swetake.util.Qrcode;
-
/**获取qrcode jar包 https://osdn.jp/projects/qrcode
-
* 生成qrcode二维码
-
* @author fangyi
-
*
-
*/
-
public class CreateQrCode {
-
public static void main(String[] args) throws Exception {
-
Qrcode qrcode= new Qrcode();
-
qrcode.setQrcodeErrorCorrect('M');//纠错等级
-
qrcode.setQrcodeEncodeMode('B');//N代表数字 A代表字母 B代表其他
-
qrcode.setQrcodeVersion(7);//版本
-
String qrData ="www.baidu.com";//二维码信息内容
-
int width=67+12*(7-1);
-
int height=67+12*(7-1);
-
-
BufferedImage bufferedImage = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
-
//画图工具
-
Graphics2D gs= bufferedImage.createGraphics();
-
//设置属性
-
gs.setBackground(Color.WHITE);
-
gs.setColor(Color.BLACK);
-
gs.clearRect(0, 0, width, height);
-
//填充
-
int pixoff=2;//偏移量
-
byte[] d = qrData.getBytes("gb2312");//编码防止有中文
-
if (0 < d.length && d.length<120) {
-
boolean[][] s = qrcode.calQrcode(d);
-
for (int i = 0; i < s.length; i++) {
-
for (int j = 0; j < s.length; j++) {
-
if(s[j][i]){
-
gs.fillRect(i*3+pixoff, j*3+pixoff, 3, 3);
-
}
-
}
-
}
-
}
-
//关闭资源,并保存文件
-
gs.dispose();
-
bufferedImage.flush();
-
ImageIO.write(bufferedImage, "png", new File("D:/qrcode.jpg"));//输出到指定地方
-
}
-
}
读取指定的二维码:
-
import java.awt.image.BufferedImage;
-
import java.io.File;
-
import java.io.IOException;
-
-
import javax.imageio.ImageIO;
-
-
import jp.sourceforge.qrcode.QRCodeDecoder;
-
/**
-
* 读取制定路径下的qrcode信息
-
* @author fangyi
-
*
-
*/
-
public class ReaderQrcode {
-
-
public static void main(String[] args) throws IOException {
-
//指定的二维码文件路径
-
File file= new File("D:/jqueryqrcode.png");
-
BufferedImage bufferedImage = ImageIO.read(file);
-
QRCodeDecoder qrCodeDecoder = new QRCodeDecoder();
-
String result = new String(qrCodeDecoder.decode(new MyQRCodeImage(bufferedImage)),"gb2312");
-
//输出结果
-
System.out.println(result);
-
bufferedImage.flush();
-
}
-
}
-
-
-
import java.awt.image.BufferedImage;
-
-
import jp.sourceforge.qrcode.data.QRCodeImage;
-
-
/**
-
* 自定义QRCodeImage类实现QRCodeImage 供读取时所用
-
* @author fangyi
-
*
-
*/
-
public class MyQRCodeImage implements QRCodeImage {
-
-
BufferedImage bufferedImage ;
-
-
public MyQRCodeImage(BufferedImage bufferedImage) {
-
super();
-
this.bufferedImage = bufferedImage;
-
}
-
-
@Override
-
public int getHeight() {
-
return bufferedImage.getHeight();
-
}
-
-
@Override
-
public int getPixel(int arg0, int arg1) {
-
return bufferedImage.getRGB(arg0, arg1);
-
}
-
-
@Override
-
public int getWidth() {
-
return bufferedImage.getWidth();
-
}
-
-
}
第二种:创建动态的web工程 依赖jquery.qrcode.min.js jquery.js 运行工程访问下面jsp就可以了
-
<%@ page language="java" contentType="text/html; charset=UTF-8"
-
pageEncoding="UTF-8"%>
-
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
-
<html>
-
<head>
-
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
-
<title>生成二维码</title>
-
<!-- js地址https://github.com/jeromeetienne/jquery-qrcode -->
-
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery.min.js"></script>
-
<script type="text/javascript" src="<%=request.getContextPath() %>/js/jquery.qrcode.min.js"></script>
-
</head>
-
<body>
-
生成二维码如下:<br><br><br>
-
<div id="qrcode"></div>
-
-
<script type="text/javascript">
-
$('#qrcode').qrcode("www.baidu.com"); //生产二维码
-
/* jquery('#qrcode').qrcode({width: 64,height: 64,text: "size doesn't matter"}); */
-
</script>
-
-
</body>
-
</html>
第三种 创建Java project 依赖zxing3.2.1.jar
-
import java.io.File;
-
import java.io.IOException;
-
import java.util.Hashtable;
-
-
import com.google.zxing.BarcodeFormat;
-
import com.google.zxing.EncodeHintType;
-
import com.google.zxing.MultiFormatWriter;
-
import com.google.zxing.WriterException;
-
import com.google.zxing.common.BitMatrix;
-
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
-
/**
-
* zxing jar包地址 https://github.com/Candy1575/QRcode
-
* 依赖MatrixToImageWriter类
-
* @author fangyi
-
*
-
*/
-
public class EncodeTest {
-
-
public static void Encode_QR_CODE() throws IOException, WriterException{
-
String contents = "ZXing 二维码内容1234!"; // 二维码内容
-
int width = 430; // 二维码图片宽度 300
-
int height = 430; // 二维码图片高度300
-
-
String format = "gif";// 二维码的图片格式 gif
-
-
Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>();
-
// 指定纠错等级,纠错级别(L 7%、M 15%、Q 25%、H 30%)
-
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
-
// 内容所使用字符集编码
-
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
-
// hints.put(EncodeHintType.MAX_SIZE, 350);//设置图片的最大值
-
// hints.put(EncodeHintType.MIN_SIZE, 100);//设置图片的最小值
-
hints.put(EncodeHintType.MARGIN, 1);//设置二维码边的空度,非负数
-
-
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents,//要编码的内容
-
//编码类型,目前zxing支持:Aztec 2D,CODABAR 1D format,Code 39 1D,Code 93 1D ,Code 128 1D,
-
//Data Matrix 2D , EAN-8 1D,EAN-13 1D,ITF (Interleaved Two of Five) 1D,
-
//MaxiCode 2D barcode,PDF417,QR Code 2D,RSS 14,RSS EXPANDED,UPC-A 1D,UPC-E 1D,UPC/EAN extension,UPC_EAN_EXTENSION
-
BarcodeFormat.QR_CODE,
-
width, //条形码的宽度
-
height, //条形码的高度
-
hints);//生成条形码时的一些配置,此项可选
-
-
// 生成二维码
-
File outputFile = new File("D:" + File.separator + "mycode.gif");//指定输出路径
-
-
MatrixToImageWriter.writeToFile(bitMatrix, format, outputFile);
-
}
-
-
public static void main(String[] args) throws Exception {
-
try {
-
Encode_QR_CODE();
-
} catch (Exception e) {
-
// TODO: handle exception
-
e.printStackTrace();
-
}
-
}
-
-
}
-
-
-
import java.awt.image.BufferedImage;
-
import java.io.File;
-
import java.io.IOException;
-
import java.io.OutputStream;
-
-
import javax.imageio.ImageIO;
-
-
import com.google.zxing.common.BitMatrix;
-
-
/**
-
* 二维码的生成需要借助MatrixToImageWriter类,
-
* 该类是由Google提供的,可以将该类直接拷贝到源码中使用,当然你也可以自己写个
-
* 生产条形码的基类 依赖LogoConfig类
-
*/
-
public class MatrixToImageWriter {
-
private static final int BLACK = 0xFF000000;//用于设置图案的颜色
-
private static final int WHITE = 0xFFFFFFFF; //用于背景色
-
-
private MatrixToImageWriter() {
-
}
-
-
public static BufferedImage toBufferedImage(BitMatrix matrix) {
-
int width = matrix.getWidth();
-
int height = matrix.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, (matrix.get(x, y) ? BLACK : WHITE));
-
// image.setRGB(x, y, (matrix.get(x, y) ? Color.YELLOW.getRGB() : Color.CYAN.getRGB()));
-
}
-
}
-
return image;
-
}
-
-
public static void writeToFile(BitMatrix matrix, String format, File file) throws IOException {
-
BufferedImage image = toBufferedImage(matrix);
-
//设置logo图标
-
LogoConfig logoConfig = new LogoConfig();
-
image = logoConfig.LogoMatrix(image);
-
-
if (!ImageIO.write(image, format, file)) {
-
throw new IOException("Could not write an image of format " + format + " to " + file);
-
}else{
-
System.out.println("图片生成成功!");
-
}
-
}
-
-
public static void writeToStream(BitMatrix matrix, String format, OutputStream stream) throws IOException {
-
BufferedImage image = toBufferedImage(matrix);
-
//设置logo图标
-
LogoConfig logoConfig = new LogoConfig();
-
image = logoConfig.LogoMatrix(image);
-
-
if (!ImageIO.write(image, format, stream)) {
-
throw new IOException("Could not write an image of format " + format);
-
}
-
}
-
}
-
-
-
-
import java.awt.BasicStroke;
-
import java.awt.Color;
-
import java.awt.Graphics2D;
-
import java.awt.geom.RoundRectangle2D;
-
import java.awt.image.BufferedImage;
-
import java.io.File;
-
import java.io.IOException;
-
import javax.imageio.ImageIO;
-
/**
-
* 二维码 添加自定义 logo图标 处理的方法,
-
* 模仿微信自动生成二维码效果,有圆角边框,logo和二维码间有空白区,logo带有灰色边框
-
* @author fangyi
-
*
-
*/
-
public class LogoConfig {
-
-
/**
-
* 设置 logo
-
* @param matrixImage 源二维码图片
-
* @return 返回带有logo的二维码图片
-
* @throws IOException
-
* @author Administrator sangwenhao
-
*/
-
public BufferedImage LogoMatrix(BufferedImage matrixImage) throws IOException{
-
/**
-
* 读取二维码图片,并构建绘图对象
-
*/
-
Graphics2D g2 = matrixImage.createGraphics();
-
-
int matrixWidth = matrixImage.getWidth();
-
int matrixHeigh = matrixImage.getHeight();
-
-
/**
-
* 读取Logo图片
-
*/
-
BufferedImage logo = ImageIO.read(new File("C:\\Users\\fangyi\\Pictures\\code-wallpaper-18.png"));
-
-
//开始绘制图片
-
g2.drawImage(logo,matrixWidth/5*2,matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5, null);//绘制
-
BasicStroke stroke = new BasicStroke(5,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
-
g2.setStroke(stroke);// 设置笔画对象
-
//指定弧度的圆角矩形
-
RoundRectangle2D.Float round = new RoundRectangle2D.Float(matrixWidth/5*2, matrixHeigh/5*2, matrixWidth/5, matrixHeigh/5,20,20);
-
g2.setColor(Color.white);
-
g2.draw(round);// 绘制圆弧矩形
-
-
//设置logo 有一道灰色边框
-
BasicStroke stroke2 = new BasicStroke(1,BasicStroke.CAP_ROUND,BasicStroke.JOIN_ROUND);
-
g2.setStroke(stroke2);// 设置笔画对象
-
RoundRectangle2D.Float round2 = new RoundRectangle2D.Float(matrixWidth/5*2+2, matrixHeigh/5*2+2, matrixWidth/5-4, matrixHeigh/5-4,20,20);
-
g2.setColor(new Color(128,128,128));
-
g2.draw(round2);// 绘制圆弧矩形
-
-
g2.dispose();
-
matrixImage.flush() ;
-
return matrixImage ;
-
}
-
-
}
读取二维码信息
-
import java.awt.image.BufferedImage;
-
import java.io.File;
-
import java.io.IOException;
-
import java.util.HashMap;
-
import java.util.Map;
-
import javax.imageio.ImageIO;
-
import com.google.zxing.Binarizer;
-
import com.google.zxing.BinaryBitmap;
-
import com.google.zxing.EncodeHintType;
-
import com.google.zxing.LuminanceSource;
-
import com.google.zxing.MultiFormatReader;
-
import com.google.zxing.NotFoundException;
-
import com.google.zxing.Result;
-
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
-
import com.google.zxing.common.BitArray;
-
import com.google.zxing.common.BitMatrix;
-
import com.google.zxing.common.HybridBinarizer;
-
-
/**
-
* 读取zxing类型下的二维码信息
-
* @author fangyi
-
*
-
*/
-
public class ReadQrCode_Zxing {
-
-
@SuppressWarnings("unchecked")
-
public static void main(String[] args) {
-
try {
-
MultiFormatReader formatReader = new MultiFormatReader();
-
//读取指定的二维码文件
-
File file= new File("D:\\mycode.gif");
-
BufferedImage bufferedImage =ImageIO.read(file);
-
BinaryBitmap binaryBitmap= new BinaryBitmap(new HybridBinarizer(new BufferedImageLuminanceSource(bufferedImage)));
-
//定义二维码参数
-
Map hints= new HashMap<>();
-
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
-
Result result = formatReader.decode(binaryBitmap, hints);
-
//输出相关的二维码信息
-
System.out.println("解析结果"+result.toString());
-
System.out.println("二维码格式类型"+result.getBarcodeFormat());
-
System.out.println("二维码文本内容"+result.getText());
-
bufferedImage.flush();
-
} catch (NotFoundException e) {
-
e.printStackTrace();
-
} catch (IOException e) {
-
e.printStackTrace();
-
}
-
}
-
}
用二维码进行添加好友获取好友信息是用到VCard
微信扫码登陆网页原理:通过堵塞等待的长连接,近乎实时的获得信息。 对于验证过程,Open API 一般是通过授权令牌(Token)来解决的,原理是当用户通过授权后,分配一个限定条件下的令牌(如限制本机访问、限制授权有效时间、限制同时登录设备数等),使获得授权的用户仅在有限的前提下能访问相关服务。 像计算机休眠后曾做的授权就自动收回了,这样就有效的避免了在别人电脑上(尤其是网吧)打开,但忘记关闭或退出这类安全问题了。
实现可借鉴已有博客:https://www.cnblogs.com/zijun/p/3580125.html
java生成二维码,读取(解析)二维码图片的更多相关文章
- atitit. java jsoup html table的读取解析 总结
atitit. java jsoup html table的读取解析 总结 1. 两个大的parser ,,,jsoup 跟个 htmlparser 1 2. 资料比较 1 3. jsoup越佳. ...
- Java生成二维码和解析二维码URL
二维码依赖jar包,zxing <!-- 二维码依赖 start --><dependency> <groupId>com.google.zxing</gro ...
- java二维码之利用谷歌的zxing生成二维码,解析二维码
生成二维码 @RequestMapping("/123") public void test(HttpServletRequest request,HttpServletRespo ...
- java代码生成二维码以及解析二维码
package com.test; import java.awt.Color; import java.awt.Graphics2D; import java.awt.image.BufferedI ...
- Java并发编程中的设计模式解析(二)一个单例的七种写法
Java单例模式是最常见的设计模式之一,广泛应用于各种框架.中间件和应用开发中.单例模式实现起来比较简单,基本是每个Java工程师都能信手拈来的,本文将结合多线程.类的加载等知识,系统地介绍一下单例模 ...
- Java 自定义注解及注解读取解析--模拟框架生成SQL语句
假设们使用一张简单的表,结构如下: 定义注解: 表注解: package com.xzlf.annotation; import java.lang.annotation.ElementType; i ...
- ReactiveCocoa源码拆分解析(二)
(整个关于ReactiveCocoa的代码工程可以在https://github.com/qianhongqiang/QHQReactive下载) 上面抽丝剥茧的把最主要的信号机制给分离开了.但在RA ...
- Spring源码深度解析-《源码构建》
1.gradle构建eclipse项目时,gradle-5.0版本构建失败,gradle-3.3构建成功!Why 2.导入spring-framework-3.2.x/spring-beans之前先导 ...
- JUC 并发编程--11, AQS源码原理解析, ReentrantLock 源码解读
这里引用别人博客,不重复造轮子 https://blog.csdn.net/u012881584/article/details/105886486 https://www.cnblogs.com/w ...
- Java使用QRCode.jar生成与解析二维码
原文V:http://www.cnblogs.com/bigroc/p/7496995.html#3797682 正题:Java使用QRCode.jar生成与解析二维码demo 欢迎新手共勉,大神监督 ...
随机推荐
- 40.【IntelliJ IDEA】使用idea解决新建jsp文件而找不到jsp文件模版的新建选项
转自:https://www.cnblogs.com/sxdcgaq8080/p/7676294.html 使用idea解决新建jsp文件而找不到jsp文件模版的新建选项,这样每次创建一个新的jsp文 ...
- pt支持的格式
- 微信支付v2开发(7) 告警通知
本文介绍微信支付中如何获得告警通知. 一.告警通知 为了及时通知商户异常,提高商户在微信平台的服务质量.微信后台会向商户推送告警通知,包括发货延迟.调用失败.通知失败等情况,通知的地址是商户在申请支付 ...
- sql基础知识集锦
Sql常用语法 下列语句部分是Mssql语句,不可以在access中使用. SQL分类: DDL—数据定义语言(CREATE,ALTER,DROP,DECLARE) DML—数据操纵语言(SELECT ...
- Javascript和jquery事件--滚动条事件和自定义滚动条事件样式
很想把滚动条事件跟鼠标滚轮事件放在一起,那就直接写在这一篇了.除了事件以外,对滚动条样式的调整也记在这里吧. 滚动条是浏览器的默认事件,使用overflow:auto/scroll都有可能出现,它的默 ...
- 2.Docker初体验【Docker每天5分钟】
原文:2.Docker初体验[Docker每天5分钟] Docker给PaaS世界带来的“降维打击”,其实是提供了一种非常便利的打包机制.该机制打包了应用运行所需要的整个操作系统,从而保证了本地环境和 ...
- C#DateTime与Unix时间戳的转换
/// <summary> /// Unix时间戳转为C#格式时间 /// </summary> /// <param name="timeStamp" ...
- jquery-validate使用.md
html <form id="s_form" class="form-horizontal" action="http://www.baidu. ...
- NSArray NSDictionary一些用法
//从字符串分割到数组- componentsSeparatedByString: NSString *str = [NSString alloc] initWithString:@"a,b ...
- [Angular] Configurable Angular Components - Content Projection and Input Templates
We are going to have a modal component: <au-modal > </au-modal> And we can pass default ...