Java-ZXing-二维码

需求

新增App的版本信息时,将App的下载地址转成二维码图标,以base64的方式存储在数据库中

准备

<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>core</artifactId>
    <version>3.3.0</version>
</dependency>
<dependency>
    <groupId>com.google.zxing</groupId>
    <artifactId>javase</artifactId>
    <version>3.3.0</version>
</dependency>

关键

/**
 * 生成二维码
 *
 * @param imgPath 生成的二维码图片的保存路径
 * @param format 图片格式
 * @param content 二维码保存的信息
 * @param width
 * @param height
 * @throws Exception
 */
public static void encodeZx(String imgPath,String format,String content,int width,int height) {
    File file = new File(imgPath);
    /*
     *hints存放加密参数
     * 编码格式,排错率,
     */
    Map<EncodeHintType,Object> hints = new Hashtable<>();
    hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
    hints.put(EncodeHintType.CHARACTER_SET,"UTF-8");
    hints.put(EncodeHintType.MARGIN,1);
    try {
        //BarcodeFormat.QR_CODE:要解析的类型(二维码)
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE,width,height,hints);
        BufferedImage bufimg = new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
        for (int x=0;x < width;x++){
            for (int y=0;y<height;y++){
                bufimg.setRGB(x,y,(bitMatrix.get(x,y)? Color.BLACK:Color.WHITE).getRGB());
            }
        }
        //生成图片:format:图片格式
        ImageIO.write(bufimg,format,file);
    } catch (IOException | WriterException e) {
        String errorMsg = "生成二维码错误";
        log.error(errorMsg);
    }
}
/**
 * 图片转化成base64字符串
 *
 * @param imgPath
 * @return
 */
public static String getImageStr(String imgPath) {
    String imgFile = imgPath;
    InputStream in = null;
    byte[] data;
    // 返回Base64编码过的字节数组字符串
    String encode = null;
    // 对字节数组Base64编码
    BASE64Encoder encoder = new BASE64Encoder();
    try {
        // 读取图片字节数组
        in = new FileInputStream(imgFile);
        data = new byte[in.available()];
        in.read(data);
        encode = encoder.encode(data);
    } catch (IOException e) {
        String errorMsg = "读取图片文件错误";
        log.error(errorMsg);
        e.printStackTrace();
    } finally {
        try {
            in.close();
        } catch (IOException e) {
            String errorMsg = "图片文件流关闭错误";
            log.error(errorMsg);
            e.printStackTrace();
        }
    }
    return encode;
}

用法

图片

参考

Java常见应用——Json,二维码生成,加密解密应用

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值