import java.io.File; import java.nio.file.FileSystems; import java.nio.file.Path; import java.util.Hashtable; import com.google.zxing.BarcodeFormat; import com.google.zxing.EncodeHintType; import com.google.zxing.client.j2se.MatrixToImageWriter; import com.google.zxing.common.BitMatrix; import com.google.zxing.qrcode.QRCodeWriter; import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel; public class QRCodeUtil { private static int margin = 0; //白边大小,取值范围0~4 private static ErrorCorrectionLevel level = ErrorCorrectionLevel.L; /** * 生成二维码 保存至服务器 * @param text 二维码内容 * @param width * @param height * @param filePath 保存服务器路径 * @throws Exception */ public static void generateQRCodeImage(String text, int width, int height, String filePath,String fileName) throws Exception { File f = new File(filePath); if (!f.exists()) { try { f.mkdirs(); } catch (Exception e) { e.printStackTrace(); } } Hashtable<EncodeHintType, Object> hints = new Hashtable<EncodeHintType, Object>(); // 指定纠错等级 hints.put(EncodeHintType.ERROR_CORRECTION, level); // 指定编码格式 hints.put(EncodeHintType.CHARACTER_SET, "UTF-8"); hints.put(EncodeHintType.MARGIN, margin); //设置白边 QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(text, BarcodeFormat.QR_CODE, width, height,hints); Path path = FileSystems.getDefault().getPath(filePath+fileName); MatrixToImageWriter.writeToPath(bitMatrix, "PNG", path); } }
生成二维码的工具类
最新推荐文章于 2024-05-14 20:52:11 发布