maven依赖
<!-- 二维码依赖 -->
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>core</artifactId>
<version>3.4.0</version>
</dependency>
<dependency>
<groupId>com.google.zxing</groupId>
<artifactId>javase</artifactId>
<version>3.4.0</version>
</dependency>
<!-- 驱动摄像头 -->
<dependency>
<groupId>com.github.sarxos</groupId>
<artifactId>webcam-capture</artifactId>
<version>0.3.12</version>
</dependency>
二维码工具类
import com.google.zxing.*;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.QRCodeWriter;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;
import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.Hashtable;
/**
* zh:二维码生成工具类
* en:QR code generation tool class
*
* @author hjj
* @date 2021/07/30
*/
public class QrCodeUtil {
/**
* 二维码尺寸
* */
public static final int QRCODE_SIZE = 500;
/**
* 二维码图片转Base64字符串
*
* @param content 二维码携带信息
* @return Base64字符串
*/
public static String ImageTurnBase64(String content) {
return createQrCodeBase64(content, QRCODE_SIZE);
}
/**
* 创建二维码图片文件
*
* @param content 二维码携带信息
*/
public static void createQrCodeImage(String content) {
createQrCodeImage(content, QRCODE_SIZE,"C:\\"+content+".jpg");
}
/**
* 创建二维码图片
*
* @param content 二维码携带信息
* @param qrCodeSize 二维码图片大小
* @return Base64字符串
*/
private static String createQrCodeBase64(String content, int qrCodeSize) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
try {
BufferedImage image = createQrCode(content, qrCodeSize);
//转换成png格式的IO流
ImageIO.write(image, "png", byteArrayOutputStream);
} catch (Exception e) {
e.printStackTrace();
}
byte[] bytes = byteArrayOutputStream.toByteArray();
BASE64Encoder encoder = new BASE64Encoder();
String base64 = encoder.encodeBuffer(bytes).trim();
base64 = "data:image/png;base64," + base64;
return base64;
}
/**
* 创建二维码图片
*
* @param content 二维码携带信息
* @param qrCodeSize 二维码图片大小
* @param filePath 生成的二维码图片的保存的路径
*/
public static void createQrCodeImage(String content, int qrCodeSize, String filePath) {
try {
BufferedImage bi = createQrCode(content, qrCodeSize);
File imgFile = new File(filePath);
ImageIO.write(bi, "JPEG", imgFile);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 生成包含字符串信息的二维码图片
*
* @param content 二维码携带信息
* @param qrCodeSize 二维码图片大小
*/
public static BufferedImage createQrCode(String content, int qrCodeSize) {
if (null == content)
return null;
try {
// 设置二维码纠错级别Map
Hashtable<EncodeHintType, Object> hintMap = new Hashtable<>();
// 矫错级别
hintMap.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.L);
hintMap.put(EncodeHintType.CHARACTER_SET, "utf-8");
QRCodeWriter qrCodeWriter = new QRCodeWriter();
// 创建比特矩阵(位矩阵)的QR码编码的字符串
BitMatrix byteMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, qrCodeSize, qrCodeSize, hintMap);
// 使BufferedImage勾画QRCode (matrixWidth 是行二维码像素点)
int matrixWidth = byteMatrix.getWidth();
int matrixHeight = byteMatrix.getWidth();
BufferedImage image = new BufferedImage(matrixWidth - 65, matrixWidth - 65, BufferedImage.TYPE_INT_RGB);
image.createGraphics();
Graphics2D graphics = (Graphics2D) image.getGraphics();
graphics.setColor(Color.WHITE);
graphics.fillRect(0, 0, matrixWidth, matrixHeight);
// 使用比特矩阵画并保存图像
graphics.setColor(Color.BLACK);
for (int i = 0; i < matrixWidth; i++) {
for (int j = 0; j < matrixWidth; j++) {
if (byteMatrix.get(i, j)) {
graphics.fillRect(i - 33, j - 33, 2, 2);
}
}
}
return image;
} catch (Exception e) {
e.printStackTrace();
return null;
}
}
public static String parseQRCode(File file) {
BufferedImage bufferedImage = null;
try {
bufferedImage = ImageIO.read(file);
} catch (IOException e) {
e.printStackTrace();
}
LuminanceSource source = new BufferedImageLuminanceSource(bufferedImage);
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
Hashtable<DecodeHintType, String> hints = new Hashtable<DecodeHintType, String>();
hints.put(DecodeHintType.CHARACTER_SET, "utf-8");
Result result = null;
try {
result = new MultiFormatReader().decode(bitmap, hints);
System.out.println(result.toString());
return result.toString();
} catch (NotFoundException e) {
e.printStackTrace();
}
return null;
}
/**
* 解析二维码
*
* @param qrCodeImage 二维码图片
* @param charset 字符集(包含中文建议使用UTF-8)
* @return 解析后二维码内容
*/
public static String parseQRCode(BufferedImage qrCodeImage, String charset) throws Exception {
if (null == qrCodeImage)
return null;
// 解码设置
Hashtable<DecodeHintType, Object> hints = new Hashtable<DecodeHintType, Object>();
hints.put(DecodeHintType.CHARACTER_SET, charset); // 设定字符集
// 图像解析为亮度源
BufferedImageLuminanceSource luminanceSource = new BufferedImageLuminanceSource(qrCodeImage);
// 亮度源解析为二进制位图
BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(luminanceSource));
// 二维码解码
Result result = new MultiFormatReader().decode(bitmap, hints);
// 解析后二维码内容
return result.getText();
}
/**
* @Description: base64字符串转化成图片
* @param: imgStr Base64字符串
* @param: photoname 图片名称
* @Return: 路径地址
*/
public static String Base64TurnImage(String imgStr,String photoname)
{
//对字节数组字符串进行Base64解码并生成图片
//图像数据为空
if (imgStr == null)
return "";
BASE64Decoder decoder = new BASE64Decoder();
try
{
//Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for(int i=0;i<b.length;++i)
{
if(b[i]<0)
{
//调整异常数据
b[i]+=256;
}
}
//生成jpeg图片
String imagePath= "F:\\";
//System.currentTimeMillis()
//新生成的图片
String imgFilePath = imagePath+photoname+".png";
OutputStream out = new FileOutputStream(imgFilePath);
out.write(b);
out.flush();
out.close();
return imgFilePath;
}
catch (Exception e)
{
return e.getMessage();
}
}
/**
* @Description: 解析二维码base64字符串
* @param: imgStr Base64字符串
* @return 解析后内容
* */
public static String Base64TurnQrCode(String imgStr) {
//对字节数组字符串进行Base64解码并生成图片
//图像数据为空
if (imgStr == null)
return "";
BASE64Decoder decoder = new BASE64Decoder();
try {
//Base64解码
byte[] b = decoder.decodeBuffer(imgStr);
for (int i = 0; i < b.length; ++i) {
if (b[i] < 0) {
//调整异常数据
b[i] += 256;
}
}
ByteArrayInputStream bais = new ByteArrayInputStream(b);
// 字节转图片
BufferedImage bufferedImage = ImageIO.read(bais);
// 解析图片结果
return parseQRCode(bufferedImage, "UTF-8");
}catch (Exception e){
e.printStackTrace();
}
return "";
}
}
测试
public static void main(String[] args) throws Exception{
while (true){
//设置摄像头拍照大小 建议摄像头像素500W以上
Dimension[] nonStandardResolutions = new Dimension[] {
WebcamResolution.PAL.getSize(),
WebcamResolution.HD.getSize(),
new Dimension(4000, 2000),
new Dimension(2000, 1000),
};
Webcam webcam = Webcam.getDefault();
webcam.setCustomViewSizes(nonStandardResolutions);
webcam.setViewSize(WebcamResolution.HD.getSize());
webcam.open();
File file = new File("D:\\GitProjects\\hello-world.png");//照片存放地址
ImageIO.write(webcam.getImage(), "PNG", file);
Thread.sleep(3000);
QrCodeUtil qrCodeUtil = new QrCodeUtil();
String res = qrCodeUtil.parseQRCode(file);//解析二维码 返回二维码的数据
System.out.println(res);
Thread.sleep(5000);
}
}