目 录
1、创建项目并配置Maven和添加依赖
新建一个项目QRCodeDemo,配置好maven仓库后,在项目的pom.xml中添加依赖:
pom.xml
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>com.ljh</groupId>
<artifactId>testDemo</artifactId>
<version>1.0-SNAPSHOT</version>
<dependencies>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.3.0</version>
</dependency>
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.1</version>
<configuration>
<target>9</target>
<source>9</source>
<encoding>UTF-8</encoding>
</configuration>
</plugin>
</plugins>
</build>
</project>
2、谷歌帮助类
在项目文件夹下新建一个帮助类,类名为:BufferedImageLuminanceSource.java,这是谷歌提供的帮助类,导入包com.google.zxing.LuminanceSource即可使用。
BufferedImageLuminanceSource.java
package com.ljh.QRCode.utils;
import com.google.zxing.LuminanceSource;
import java.awt.*;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
public class BufferedImageLuminanceSource extends LuminanceSource {
private final BufferedImage image;
private final int left;
private final int top;
public BufferedImageLuminanceSource(BufferedImage image) {
this(image, 0, 0, image.getWidth(), image.getHeight());
}
public BufferedImageLuminanceSource(BufferedImage image, int left, int top, int width, int height) {
super(width, height);
int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();
if (left + width > sourceWidth || top + height > sourceHeight) {
throw new IllegalArgumentException("Crop rectangle does not fit within image data.");
}
for (int y = top; y < top + height; y++) {
for (int x = left; x < left + width; x++) {
if ((image.getRGB(x, y) & 0xFF000000) == 0) {
image.setRGB(x, y, 0xFFFFFFFF); // = white
}
}
}
this.image = new BufferedImage(sourceWidth, sourceHeight, BufferedImage.TYPE_BYTE_GRAY);
this.image.getGraphics().drawImage(image, 0, 0, null);
this.left = left;
this.top = top;
}
public byte[] getRow(int y, byte[] row) {
if (y < 0 || y >= getHeight()) {
throw new IllegalArgumentException("Requested row is outside the image: " + y);
}
int width = getWidth();
if (row == null || row.length < width) {
row = new byte[width];
}
image.getRaster().getDataElements(left, top + y, width, 1, row);
return row;
}
public byte[] getMatrix() {
int width = getWidth();
int height = getHeight();
int area = width * height;
byte[] matrix = new byte[area];
image.getRaster().getDataElements(left, top, width, height, matrix);
return matrix;
}
public boolean isCropSupported() {
return true;
}
public LuminanceSource crop(int left, int top, int width, int height) {
return new BufferedImageLuminanceSource(image, this.left + left, this.top + top, width, height);
}
public boolean isRotateSupported() {
return true;
}
public LuminanceSource rotateCounterClockwise() {
int sourceWidth = image.getWidth();
int sourceHeight = image.getHeight();
AffineTransform transform = new AffineTransform(0.0, -1.0, 1.0, 0.0, 0.0, sourceWidth);
BufferedImage rotatedImage = new BufferedImage(sourceHeight, sourceWidth, BufferedImage.TYPE_BYTE_GRAY);
Graphics2D g = rotatedImage.createGraphics();
g.drawImage(image, transform, null);
g.dispose();
int width = getWidth();
return new BufferedImageLuminanceSource(rotatedImage, top, sourceWidth - (left + width), getHeight(), width);
}
}
3、工具类
新建一个工具类:QRCodeUtil.java,设置生成的二维码的图片的名字。
QRCodeUtil.java
package com.ljh.QRCode.utils;
import com.google.zxing.*;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.geom.RoundRectangle2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.util.Hashtable;
public class QRCodeUtil {
private static final String CHARSET = "utf-8";
private static final String IMG_FORMAT_NAME = "PNG";
private static final Integer QR_CODE_SIZE = 300;
private static final Integer WIDTH = 60;
private static final Integer HEIGHT = 60;
private static BufferedImage createImage(String content, String imgPath, Boolean needCompress) throws WriterException, IOException {
Hashtable<EncodeHintType, Object> ht = new Hashtable<EncodeHintType, Object>();
ht.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
ht.put(EncodeHintType.CHARACTER_SET, CHARSET);
ht.put(EncodeHintType.MARGIN, 1);
BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, QR_CODE_SIZE, QR_CODE_SIZE, ht);
int height = bitMatrix.getHeight();
int width = bitMatrix.getWidth();
BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
for (int i = 0; i < width; i++) {
for (int j = 0; j < height; j++) {
image.setRGB(i, j, bitMatrix.get(i,j) ? 0xFF000000 : 0xFFFFFFFF);
}
}
if (imgPath == null || "".equals(imgPath)) {
return image;
}
QRCodeUtil.insertImg(image, imgPath, needCompress);
return image;
}
private static void insertImg(BufferedImage source, String imgPath, Boolean needCompress) throws IOException {
File file = new File(imgPath);
if (!file.exists()) {
System.err.println("" + imgPath + " 该文件不存在!");
throw new FileNotFoundException();
}
Image src = ImageIO.read(file);
int width = src.getWidth(null);
int height = src.getHeight(null);
if (needCompress) {
if (width > WIDTH) width = WIDTH;
if (height > WIDTH) height = WIDTH;
Image image = src.getScaledInstance(width, height, Image.SCALE_SMOOTH);
BufferedImage img = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
Graphics g = img.createGraphics();
g.dispose();
src = image;
}
Graphics2D graph = source.createGraphics();
int x = (QR_CODE_SIZE - width) / 2;
int y = (QR_CODE_SIZE - height) / 2;
graph.drawImage(src, x, y, width, height, null);
Shape shape = new RoundRectangle2D.Float(x, y, width, height, 6, 6);
graph.setStroke(new BasicStroke(3f));
graph.draw(shape);
graph.dispose();
}
public static void encode(String content, String imgPath, String destPath, Boolean needCompress) throws IOException, WriterException, ClassNotFoundException {
BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
mkdir(destPath);
ImageIO.write(image, IMG_FORMAT_NAME, new File(destPath));
}
public static BufferedImage encode(String content, String imgPath, Boolean needCompress) throws IOException, WriterException, ClassNotFoundException {
BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
return image;
}
public static void encode(String content, String imgPath, OutputStream outputStream, Boolean needCompress) throws IOException, WriterException, ClassNotFoundException {
BufferedImage image = QRCodeUtil.createImage(content, imgPath, needCompress);
ImageIO.write(image, IMG_FORMAT_NAME, outputStream);
}
public static void encode(String content, String destPath) throws ClassNotFoundException, IOException, WriterException {
QRCodeUtil.encode(content, null, destPath, false);
}
public static void encode(String content, OutputStream outputStream) throws ClassNotFoundException, IOException, WriterException {
QRCodeUtil.encode(content, null, outputStream, false);
}
public static String decode(File file) throws IOException, NotFoundException {
BufferedImage image;
image = ImageIO.read(file);
if (image == null) {
throw new IOException();
}
BufferedImageLuminanceSource source = new BufferedImageLuminanceSource(image);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Result result;
Hashtable<DecodeHintType, Object> ht = new Hashtable<DecodeHintType, Object>();
ht.put(DecodeHintType.CHARACTER_SET, CHARSET);
result = new MultiFormatReader().decode(bitmap, ht);
return result.getText();
}
public static String decode(String path) throws IOException, NotFoundException {
return QRCodeUtil.decode(new File(path));
}
private static void mkdir(String destPath) {
File file = new File(destPath);
if (!file.exists() && !file.isDirectory()) {
file.mkdirs();
}
}
}
4、主类
在test文件夹下新建一个主类:QRCodeUtilTest
QRCodeUtilTest.java
package com.ljh.QRCode.utils;
import com.google.zxing.NotFoundException;
import com.google.zxing.WriterException;
import org.junit.Test;
import java.io.File;
import java.io.IOException;
public class QRCodeUtilTest {
@Test
public void QRCodeTest() {
String text = "Java实现生成二维码(含logo)!";
String path = this.getClass().getResource("/").getPath();
String imgPath = path + "idea1.jpg";
String destPath = "test.png";
try {
QRCodeUtil.encode(text, imgPath, destPath, true);
} catch (IOException | WriterException | ClassNotFoundException e) {
e.printStackTrace();
}
try {
String str = QRCodeUtil.decode(destPath);
System.out.println(str);
} catch (IOException | NotFoundException e) {
e.printStackTrace();
}
}
@Test
public void filePathTest() {
File file = new File("idea1.jpg");
System.out.println(file.getAbsolutePath());
}
}
字段解释:
QRCodeUtil.encode(text, imgPath, destPath, true)语句中:
①text:编码到二维码中的内容,例如:“Java实现生成二维码(含logo)!”;
②imgPath:指嵌入二维码的图片路径,如果不写或者为null则生成的二维码没有logo;
③destPath:二维码生成的存放路径;
④true:指把logo进行压缩,也可以设置为“false”则不进行压缩;
QRCodeUtil.decode(destPath)语句中:
destPath:指要解析的二维码的存放路径,其返回值为String类型,即返回解析出后的内容。
5、运行生成二维码
在src\test\resources\添加图片idea1.jpg
在String text = " ";中输入Java实现生成二维码(含logo)!
运行QRCodeUtilTest类
生成的在二维码为test.png
识别生成的二维码进行解析:
如需更换二维码的logo和解析后的文本内容,只需修改如下几个地方即可