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<EncodeHintType, Object> 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; }