太强大了 | 一键生成,太强大了……
效果图相关依赖hi!我是小小,今天是本周的第二篇,本篇将会着重讲解关于Java生成二维码的功能
com.google.zxing
javase
3.3.0
相关工具类package com.bennyrhys.mall.util;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.MatrixToImageWriter;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.qrcode.QRCodeWriter;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
/**
* 描述:生成二维码工具
*/
public class QRCodeGenerator {
public static void generateQRCodeImage(String text, int width, int height, String filePath)
throws WriterException, IOException {
QRCodeWriter qrCodeWriter = new QRCodeWriter();
BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height);
Path path = FileSystems.getDefault().getPath(filePath);
MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path);
}
public static void main(String[] args) {
try {
generateQRCodeImage("Hello World", 350, 350, "E:/JAVA/mall/src/main/resources/images/QRTest.png");
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
添加service
/**
* 生成二维码
* 图片可解析出访问的支付对应订单号的支付连接
* @param orderNo 订单号
* @return 返回图片地址
*/
@Override
public String qrcode(String orderNo) {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String address = ip + ":" + request.getLocalPort();
String payUrl = "http://" + address + "/pay?orderNo=" + orderNo;
try {
QRCodeGenerator.generateQRCodeImage(payUrl, 350, 350, Constant.FILE_UPLOAD_PATH + orderNo + ".png");
} catch (WriterException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
String pngAddress = "http://" + address + "/images-dev/" + orderNo + ".png";
return pngAddress;
}
关于作者我是小小,双鱼座的程序猿,我们下期再见哦~
END
「 往期文章 」
扫描二维码
获取更多精彩
小明菜市场
评论