Java 二维码生成

2021-03-12 00:27

阅读:465

标签:decode   lombok   ase   tty   ble   try   object   idt   public   


import com.google.zxing.BarcodeFormat;
import com.google.zxing.EncodeHintType;
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 com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
import lombok.SneakyThrows;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.Base64;
import java.util.Hashtable;

 


public

class QRCodeUtil { /** * 字符集 */ private static final String CHARSET = "utf-8"; /** * 生成二维码 BufferedImage * @param content 内容 * @param width 宽 * @param height 搞 * @return BufferedImage * @throws WriterException WriterException */ public static BufferedImage genQRCode(String content,int width,int height) throws WriterException { Hashtable hints = new Hashtable(); //纠错能力 设置为M hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.M); //设置字符集 hints.put(EncodeHintType.CHARACTER_SET, CHARSET); //边缘 hints.put(EncodeHintType.MARGIN, 5); QRCodeWriter qrCodeWriter = new QRCodeWriter(); BitMatrix bitMatrix = qrCodeWriter.encode(content, BarcodeFormat.QR_CODE, width, height,hints); return MatrixToImageWriter.toBufferedImage(bitMatrix); } /** * 生成Base64 PNG字符串 * 例如: data:image/Png;base64,123123123123123132 * @param content 内容 * @param width 宽 * @param height 搞 * @return String 字符串 * @throws WriterException WriterException * @throws IOException IOException */ @SneakyThrows public static String genQRBase64(String content, int width, int height) { try { BufferedImage bufferedImage = genQRCode(content, width,height); String imageString = encodeImageToString(bufferedImage, ImageTypeEnum.PNG.getName()); return "data:image/Png;base64," + imageString; }catch (Exception ex){ throw new Exception(XdfnisBizCodeEnum.GEN_QR_CODE_ERROR.getMessage()); } } /** * Convert BufferedImage to Base64 * @param image BufferedImage * @param formatName 图片类型, ImageTypeEnum * @return String Base64 字符串 * @throws IOException 异常 */ public static String encodeImageToString(BufferedImage image, String formatName) throws IOException { String imageString ; ByteArrayOutputStream bos = new ByteArrayOutputStream(); ImageIO.write(image, formatName, bos); byte[] imageBytes = bos.toByteArray(); Base64.Encoder encoder = Base64.getEncoder(); imageString = encoder.encodeToString(imageBytes); bos.close(); return imageString; }

 

Java 二维码生成

标签:decode   lombok   ase   tty   ble   try   object   idt   public   

原文地址:https://www.cnblogs.com/xiaoyu369/p/14091570.html

上一篇:win10下安装vue

下一篇:python正则表达式


评论


亲,登录后才可以留言!