准备:生成带logo的二维码时,logo图片必须存在;不存在则生成无logo的二维码。
1、建立Maven项目,并引入jar包。
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.2.0</version>
</dependency>
2、编码
import java.awt.BasicStroke;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Shape;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.util.HashMap;
import java.util.Map;
import java.util.Random;
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.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.Result;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.client.j2se.MatrixToImageConfig;
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;
public class QRCode {
private static final String CHARSET = "utf-8";
private static final String FORMAT_NAME = "png";
// 二维码尺寸
private static final int QRCODE_SIZE = 300;
// LOGO宽度
private static final int WIDTH = 60;
// LOGO高度
private static final int HEIGHT = 60;
public static String decode(String path) throws Exception {
return QRCode.decode(new File(path));
}
/**
* 从二维码中解析数据
* @param file 二维码图片文件
* @return 返回从二维码中解析到的数据值
* @throws Exception
* @author wanmm
* @date 2017年9月12日
*/
public static String decode(File file) throws Exception{
BufferedImage image = ImageIO.read(file);//图片缓存对象
if(image ==null)
return null;
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
//BinaryBitmap 解码二进制位图
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
/* Hashtable hints = new Hashtable();
可用下面的Map对象替换
*/
Map<DecodeHintType,Object> hints = new HashMap<DecodeHintType,Object>();
//设置字符串解码格式
hints.put(DecodeHintType.CHARACTER_SET, CHARSET);
//Result封装在图像中的解码结果
Result result = new MultiFormatReader().decode(bitmap, hints);
return result.getText();
}
/**
* 生成带logo二维码,并保存到磁盘中
* @param content 二维码内容
* @param imgPath 二维码中插入的logo的图片路径
* @param destPath 目标路径
* @param needCompress 是否压缩logo的大小
* @throws Exception
* @author wanmm
* @date 2017年9月12日
*/
public static void encode(String content,String imgPath,String destPath,boolean needCompress) throws Exception{
BufferedImage image = QRCode.createImage(content, imgPath, needCompress);
mkdirs(destPath);
String file = new Random().nextInt(99999999) + ".png";//生成随机文件名
ImageIO.write(image, FORMAT_NAME, new File(destPath + "/" + file));
}
public static void mkdirs(String destPath){
File file = new File(destPath);
if(!file.exists() && !file.isDirectory()){
file.mkdirs();
}
}
/**
* 生成二维码
* @param contend 二维码内容
* @param imgPath 二维码中插入的logo的图片路径
* @param needCompress 是否压缩logo的大小
* @return 二维码图片
* @throws Exception
* @author wanmm
* @date 2017年9月12日
*/
public static BufferedImage createImage(String content,String imgPath,boolean needCompress) throws Exception{
Map<EncodeHintType,Object> hints = new HashMap<EncodeHintType,Object>();
//纠错程度
hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
//字符编码
hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
//生成条形码时使用的空白值。单位:像素
hints.put(EncodeHintType.MARGIN, 1);
//二维码的描述对象
BitMatrix bitMatrix = new MultiFormatWriter().encode(content
, BarcodeFormat.QR_CODE, QRCODE_SIZE, QRCODE_SIZE,hints);
/*int width = bitMatrix.getWidth();
int height = bitMatrix.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++){
//bitMatrix.get获取所请求的点
image.setRGB(x, y, bitMatrix.get(x, y)? 0xFF000000 : 0xFFFFFFFF);
}
}*/
MatrixToImageConfig config = new MatrixToImageConfig(0xFF000001, 0xFFFFFFFF);
BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix, config);
if(imgPath == null || "".equals(imgPath)){
return image;
}
//二维码中加入logo
QRCode.insertImage(image, imgPath, needCompress);
return image;
}
/**
* 在生成的二维码中插入logo图片
* @param source 二维码图片
* @param imgPath logo路径
* @param needCompress 是否压缩logo的大小
* @throws Exception
* @author wanmm
* @date 2017年9月12日
*/
private static void insertImage(BufferedImage source,String imgPath,boolean needCompress) throws Exception{
File file = new File(imgPath);
if(!file.exists()){
System.err.println(imgPath+" 该文件不存在");
return;
}
Image logoImg = ImageIO.read(file);
int width = logoImg.getWidth(null);
int height = logoImg.getHeight(null);
if(needCompress){
if(width > WIDTH)
width = WIDTH;
if(height > HEIGHT)
height = HEIGHT;
//创建压缩图像
Image img = logoImg.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage tag = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
// 绘制缩小后的图
Graphics g = tag.getGraphics();
g.drawImage(img, 0, 0, null);
g.dispose();
logoImg = img;
}
//插入logo图片
Graphics2D graph = source.createGraphics();
// 计算图片放置位置
int x = (QRCODE_SIZE-width)/2;
int y = (QRCODE_SIZE-height)/2;
graph.drawImage(logoImg, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, height, 6, 6);
//设置图形画线的宽度为3
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
public static void encode(String content, String imgPath, String destPath) throws Exception {
QRCode.encode(content, imgPath, destPath, false);
}
public static void encode(String content, String destPath, boolean needCompress) throws Exception {
QRCode.encode(content, null, destPath, needCompress);
}
public static void encode(String content, String destPath) throws Exception {
QRCode.encode(content, null, destPath, false);
}
}
3 测试
public static void main(String[] args) throws Exception {
//生成带logo 的二维码
String text = "http://www.csdn.net/";
QRCode.encode(text, "d:/img/tximg.png", "d:/img", true);
//生成不带logo 的二维码
String textt = "http://www.baidu.com";
QRCode.encode(textt,"","d:/img",true);
//指定二维码图片,解析返回数据
System.out.println(QRCodeUtil.decode("D:/img/61679114.png"));
}
参考: 点击打开链接