zoukankan      html  css  js  c++  java
  • Java 二维码生成

    
    
    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; }
  • 相关阅读:
    VFP获取 SQL Server 的数据表、触发器、存储过程、视图等脚本
    VFP控制Excel操作集
    MS SqlServer 的日期格式化函数 Convert
    VFP 图形文件与剪切板互换的API解决方法
    VFP中OCX控件注册检测及自动注册
    VFP检测SQL Server的五个实例代码
    缓存方案笔记
    windows访问控制列表 --ACL(Access Control List)
    cnblog排版
    GIT常用命令
  • 原文地址:https://www.cnblogs.com/xiaoyu369/p/14091570.html
Copyright © 2011-2022 走看看