JAVA二维码编码&解码
QRCodeUtil.java
package web;
import java.awt.AlphaComposite;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.RenderingHints;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Hashtable;
import java.util.Map;
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.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.ReaderException;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
* 二维码编码&解码
* @Author: ChenGuiYong 2015年7月13日 上午11:09:56
* @Version: $Id$
* @Desc: <p></p>
*/
public class QRCodeUtil {
private static final int BLACK = 0xFF000000;
private static final int WHITE = 0xFFFFFFFF;
/*
* 解码:
* 1 将图片反解码为二维矩阵
* 2 将该二维矩阵解码为内容
* */
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void decode(String imgPath) {
try {
File file = new File(imgPath);//获取该图片文件
BufferedImage image;
try {
image = ImageIO.read(file);
if (image == null) {
System.out.println("Could not decode image");
}
LuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable hints = new Hashtable();//将图片反解码为二维矩阵
hints.put(DecodeHintType.CHARACTER_SET, "UTF-8");
result = new MultiFormatReader().decode(bitmap, hints);//将该二维矩阵解码成内容
String resultStr = result.getText();
System.out.println("解码结果:"+resultStr);
} catch (IOException ioe) {
System.out.println(ioe.toString());
} catch (ReaderException re) {
System.out.println(re.toString());
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
/**
* 编码
* @author ChenGuiYong
* @data 2015年7月13日 上午11:06:20
* @param contents
* @param width
* @param height
* @param imgPath
* @param logoPath
* @return
*/
public static boolean encode(String contents, int width, int height, String imgPath,String logoPath) {
Map<EncodeHintType, Object> hints = new Hashtable<>();
// 指定纠错等级
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
// 指定编码格式
hints.put(EncodeHintType.CHARACTER_SET, "utf-8");
//设置二维码内容到边框的距离
hints.put(EncodeHintType.MARGIN, 1);
String format = "png";
try {
BitMatrix bitMatrix = new MultiFormatWriter().encode(contents, BarcodeFormat.QR_CODE, width, height, hints);
MatrixToImageWriter.writeToStream(bitMatrix, format ,new FileOutputStream(imgPath));
File qrcodeFile = new File(imgPath);
//增加logo
writeToLogo(bitMatrix,format , qrcodeFile, logoPath);
} catch (Exception e) {
return false;
}
System.out.println("编码成功!");
return true;
}
/**
* 增加Logo
* @author ChenGuiYong
* @data 2015年7月13日 上午11:07:00
* @param matrix
* @param format
* @param file
* @param logoPath
* @throws IOException
*/
public static void writeToLogo(BitMatrix matrix,String format,File file,String logoPath) throws IOException {
Graphics2D graphics2 = null;
BufferedImage image = null;
BufferedImage logo = null;
try {
/**
* 读取二维码图片,并构建绘图对象
*/
image = toBufferedImage(matrix);
graphics2 = image.createGraphics();
/**
* 读取Logo图片
*/
logo = ImageIO.read(new File(logoPath));
int codeWidth = image.getWidth();
int codeHeight = image.getHeight();
/**
* 设置logo的大小,设置为二维码图片的25%,因为过大会盖掉二维码
*/
int widthLogo = logo.getWidth(null)>codeWidth*2/13?(codeWidth*2/13):logo.getWidth(null),
heightLogo = logo.getHeight(null)>codeHeight*2/13?(codeHeight*2/13):logo.getWidth(null);
/**
* 计算图片放置位置
* logo放在中心
*/
int x = (codeWidth - widthLogo) / 2;
int y = (codeHeight - heightLogo) / 2;
int radius = 14;//圆角范围
//填充与logo大小类似的扁平化圆角矩形背景
graphics2.setComposite(AlphaComposite.Src);
graphics2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
graphics2.setColor(Color.WHITE);
graphics2.fill(new RoundRectangle2D.Float(x-2, y-2, widthLogo+4, heightLogo+4,radius,radius));
graphics2.setComposite(AlphaComposite.SrcAtop);
//开始绘制logo图片
graphics2.drawImage(logo, x, y, widthLogo, heightLogo, null);
if(!ImageIO.write(image, format, file)){
throw new IOException("Could not write an image of format " + format + " to " + file);
}
} catch (Exception e) {
throw e;
}finally{
if(graphics2!=null){
graphics2.dispose();
}
if(logo!=null){
logo.flush();
}
if(image!=null){
image.flush();
}
}
}
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);
}
}
return image;
}
public static void main(String[] args) {
String contents="http://www.baidu.com";
String imgPath = "D:/zxing/zxing.png";
String logoPath = "D:/logo.png";
QRCodeUtil.encode(contents, 200, 200, imgPath,logoPath);
QRCodeUtil.decode(imgPath);
}
}
JAVA二维码编码&解码的更多相关文章
- java 二维码编码解码
做一个小项目的时候写了个二维码编码和解码的小工具,感觉可能用得到,有兴趣的朋友可以看下 再次之前,徐需要用到google的zxing相关的jar包,还有javax相关包 以上为可能用到的jar pac ...
- Java二维码的解码和编码
原文:http://www.open-open.com/code/view/1430906793866 import java.io.File; import java.util.Hashtable; ...
- Java利用QRCode.jar包实现二维码编码与解码
QRcode是日本人94年开发出来的.首先去QRCode的官网http://swetake.com/qrcode/java/qr_java.html,把要用的jar包下下来,导入到项目里去.qrcod ...
- Java二维码生成与解码
基于google zxing 的Java二维码生成与解码 一.添加Maven依赖(解码时需要上传二维码图片,所以需要依赖文件上传包) <!-- google二维码工具 --> &l ...
- 二维码编码与解码类库ThoughtWorks.QRCode
官方地址:https://www.codeproject.com/Articles/20574/Open-Source-QRCode-Library 有源代码和示例程序 支持二维码编码(生成)和解码( ...
- Atitit java 二维码识别 图片识别
Atitit java 二维码识别 图片识别 1.1. 解码11.2. 首先,我们先说一下二维码一共有40个尺寸.官方叫版本Version.11.3. 二维码的样例:21.4. 定位图案21.5. 数 ...
- Java 二维码--转载
周末试用下Android手机的二维码扫描软件,扫描了下火车票.名片等等,觉得非常不错很有意思的.当然Java也可以实现这些,现在就分享下如何简单用Java实现二维码中QRCode的编码和解码(可以手机 ...
- java二维码生成-谷歌(Google.zxing)开源二维码生成学习及实例
java二维码生成-谷歌(Google.zxing)开源二维码生成的实例及介绍 我们使用比特矩阵(位矩阵)的QR码编码在缓冲图片上画出二维码 实例有以下一个传入参数 OutputStream ou ...
- Halcon一维码和二维码的解码步骤和技巧——第11讲
针对Halcon中一维码和二维码的解码,我分别写了两篇文章,参见: <Halcon的一维条码解码步骤和解码技巧>:https://www.cnblogs.com/xh6300/p/1048 ...
随机推荐
- 基于libcurl的restfull接口 post posts get gets
头文件 #pragma once #ifndef __HTTP_CURL_H__ #define __HTTP_CURL_H__ #include <string> #include &q ...
- C++的重载(overload)与重写(override)
C++的重载(overload)与重写(override) 成员函数被重载的特征:(同一层级类中来实现)(1)相同的范围(在同一个类中):(2)函数名字相同:名称和返回类型相同(3)参数不同:(4)v ...
- leetcode题目19.删除链表的倒数第N个节点(中等)
题目描述: 给定一个链表,删除链表的倒数第 n 个节点,并且返回链表的头结点. 示例: 给定一个链表: 1->2->3->4->5, 和 n = 2. 当删除了倒数第二个节点后 ...
- 代码优化-多态代替IF条件判断
场景描述 在开发的场景中,常常会遇到打折的业务需求,每个用户对应的等级,他们的打折情况也是不一样的.例如普通会员打9折,青铜会员打8.5折,黄金会员打8折等等.在一般开发中最简单的就是判断用户的等级, ...
- TCP输入 之 tcp_v4_rcv
tcp_v4_rcv函数为TCP的总入口,数据包从IP层传递上来,进入该函数:其协议操作函数结构如下所示,其中handler即为IP层向TCP传递数据包的回调函数,设置为tcp_v4_rcv: sta ...
- 重入锁 ReentrantLock (转)(学习记录)
重入锁(ReentrantLock)是一种递归无阻塞的同步机制.以前一直认为它是synchronized的简单替代,而且实现机制也不相差太远.不过最近实践过程中发现它们之间还是有着天壤之别. 以下是官 ...
- Canvas学习:封装Canvas绘制基本图形API
Canvas学习:封装Canvas绘制基本图形API Canvas Canvas学习 从前面的文章中我们了解到,通过Canvas中的CanvasRenderingContext2D对象中的属性和方 ...
- mongdb group聚合操作
1.数据准备 [{"goods_id":1,"cat_id":4,"goods_name":"KD876"," ...
- docker解决没有vim问题
正确(1)下载镜像,docker pull nginx(2)启动容器,docker run -d -p 8083:80 nginx[root@ceshi ~]# docker exec -it 8ca ...
- GO-REDIS的一些高级用法
1. 前言 说到Golang的Redis库,用到最多的恐怕是redigo 和 go-redis.其中 redigo 不支持对集群的访问.本文想聊聊go-redis 2个高级用法 2. 开启对Clust ...