美文网首页
二维码生成工具类

二维码生成工具类

作者: 盗生一 | 来源:发表于2020-08-31 12:31 被阅读0次
package com.hjkj.qrcode.utils;

import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.util.*;
import javax.imageio.ImageIO;
import com.google.zxing.BarcodeFormat;
import com.google.zxing.Binarizer;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.EncodeHintType;
import com.google.zxing.LuminanceSource;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.MultiFormatWriter;
import com.google.zxing.NotFoundException;
import com.google.zxing.Result;
import com.google.zxing.WriterException;
import com.google.zxing.client.j2se.BufferedImageLuminanceSource;
import com.google.zxing.common.BitMatrix;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.qrcode.decoder.ErrorCorrectionLevel;
/**
 * 二维码生成解析工具类
 */
public class QrCodeUtils {

    // 二维码颜色==黑色
    private static final int BLACK = 0xFF000000;
    // 二维码颜色==白色
    private static final int WHITE = 0xFFFFFFFF;
    // 二维码图片格式==jpg和png两种
    private static final List<String> IMAGE_TYPE = new ArrayList<>();

    static {
        IMAGE_TYPE.add("jpg");
        IMAGE_TYPE.add("png");
    }


    /**
     * 生成没有logo的二维码
     * @param content  二维码包含的内容,文本或网址
     * @param path     生成的二维码图片存放位置
     * @param size     生成的二维码图片尺寸 可以自定义或者默认(250)
     * @return         生成的二维码文件名
     */
    public static String qrCodeGenerate(String content,String path,Integer size){
        return zxingCodeCreate(content, path, size, null);
    }
    /**
     * 生成带有logo的二维码
     * @param content  二维码包含的内容,文本或网址
     * @param path     生成的二维码图片存放位置
     * @param size     生成的二维码图片尺寸 可以自定义或者默认(250)
     * @param logoPath logo图片存放位置
     * @return         生成的二维码文件名
     */
    public static String qrCodeGenerate(String content,String path,Integer size,String logoPath){
        return zxingCodeCreate(content, path, size, logoPath);
    }

    /**
     * 二维码的解析方法
     *
     * @param path 二维码图片目录
     * @return
     */
    public static Result qrCodeAnalyze(String path) {
        try {
            MultiFormatReader formatReader = new MultiFormatReader();
            File file = new File(path);
            if (file.exists()) {
                BufferedImage image = ImageIO.read(file);
                LuminanceSource source = new BufferedImageLuminanceSource(image);
                Binarizer binarizer = new HybridBinarizer(source);
                BinaryBitmap binaryBitmap = new BinaryBitmap(binarizer);
                Map hints = new HashMap();
                hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
                Result result = formatReader.decode(binaryBitmap, hints);
                return result;
            }
        } catch (IOException e) {
            e.printStackTrace();
        } catch (NotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }


    /**
     * zxing方式生成二维码
     * 注意:
     * 1,文本生成二维码的方法独立出来,返回image流的形式,可以输出到页面
     * 2,设置容错率为最高,一般容错率越高,图片越不清晰, 但是只有将容错率设置高一点才能兼容logo图片
     * 3,logo图片默认占二维码图片的20%,设置太大会导致无法解析
     *
     * @param content  二维码包含的内容,文本或网址
     * @param path     生成的二维码图片存放位置
     * @param size     生成的二维码图片尺寸 可以自定义或者默认(250)
     * @param logoPath logo的存放位置
     * @return 文件名
     */
    private static String zxingCodeCreate(String content, String path, Integer size, String logoPath) {
        try {
            //图片类型
            String imageType = "jpg";
            //获取二维码流的形式,写入到目录文件中
            BufferedImage image = getBufferedImage(content, size, logoPath);
            // 上传文件名
            String qrFileName = String.format("qr-%s.jpg",UUID.randomUUID().toString() + "_" + System.currentTimeMillis());
            //生成二维码存放文件:   // 文件对象创建后,指定的文件或目录不一定物理上存在
            File file = new File(path,qrFileName);
            if (!file.exists()) {
                file.mkdirs();
            }
            ImageIO.write(image, imageType, file);
            return qrFileName;
        } catch (IOException e) {
            e.printStackTrace();
            return null;
        }
    }


    /**
     * 二维码流的形式,包含文本内容
     *
     * @param content  二维码文本内容
     * @param size     二维码尺寸
     * @param logoPath logo的存放位置
     * @return
     */
    private static BufferedImage getBufferedImage(String content, Integer size, String logoPath) {
        if (size == null || size <= 0) {
            size = 250;
        }
        BufferedImage image = null;
        try {
            // 设置编码字符集
            Map<EncodeHintType, Object> hints = new HashMap<>();
            //设置编码
            hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
            //设置容错率最高
            hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
            hints.put(EncodeHintType.MARGIN, 1);
            // 1、生成二维码
            MultiFormatWriter multiFormatWriter = new MultiFormatWriter();
            BitMatrix bitMatrix = multiFormatWriter.encode(content, BarcodeFormat.QR_CODE, size, size, hints);
            // 2、获取二维码宽高
            int codeWidth = bitMatrix.getWidth();
            int codeHeight = bitMatrix.getHeight();
            // 3、将二维码放入缓冲流
            image = new BufferedImage(codeWidth, codeHeight, BufferedImage.TYPE_INT_RGB);
            for (int i = 0; i < codeWidth; i++) {
                for (int j = 0; j < codeHeight; j++) {
                    // 4、循环将二维码内容定入图片
                    image.setRGB(i, j, bitMatrix.get(i, j) ? BLACK : WHITE);
                }
            }
            //判断是否写入logo图片
            if (logoPath != null && !"".equals(logoPath)) {
                File logoPic = new File(logoPath);
                if (logoPic.exists()) {
                    Graphics2D g = image.createGraphics();
                    BufferedImage logo = ImageIO.read(logoPic);
                    int widthLogo = logo.getWidth(null) > image.getWidth() * 2 / 10 ? (image.getWidth() * 2 / 10) : logo.getWidth(null);
                    int heightLogo = logo.getHeight(null) > image.getHeight() * 2 / 10 ? (image.getHeight() * 2 / 10) : logo.getHeight(null);
                    int x = (image.getWidth() - widthLogo) / 2;
                    int y = (image.getHeight() - heightLogo) / 2;
                    // 开始绘制图片
                    g.drawImage(logo, x, y, widthLogo, heightLogo, null);
                    g.drawRoundRect(x, y, widthLogo, heightLogo, 15, 15);
                    //边框宽度
                    g.setStroke(new BasicStroke(2));
                    //边框颜色
                    g.setColor(Color.WHITE);
                    g.drawRect(x, y, widthLogo, heightLogo);
                    g.dispose();
                    logo.flush();
                    image.flush();
                }
            }
        } catch (WriterException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return image;
    }

}
图片.png

相关文章

  • Android----生成二维码

    引用了 ...... 导入包名 生成二维码 使用代码 工具类

  • java生成二维码

    1.pom文件添加maven依赖: 2.生成二维码工具类:

  • 二维码生成,包含文本,网址,图片等

    二维码所引入的jar包 pom文件配置 二维码生成工具类,可自行修改

  • 项目常用工具类:二维码生成

    有些项目中需要用到二维码,这里我们编写一个二维码生成的工具类。 我们需要用到zxing这个二维码工具类,然后再封装...

  • Java工具类整理

    以下整理常用的java工具类。 工具类所需要的依赖以maven的形式给出 ZXingUtils 用于二维码的生成和...

  • 使用zxing生成二维码去除白边

    生成二维码的时候,我们通常使用google.zxing包,使用google提供的工具类生成二维码的时候通常会带有白...

  • 开发相关网站

    工具类 SQL 美化 二维码生成-草料网 Base64加密、解密 - 站长工具 在线JSON校验格式化工具(Be ...

  • 使用QR Code生成二维码

    一、引入qr code相关jar包 二、生成二维码Util 三、调用工具类encode方法绘制二维码

  • Java生成二维码

    1、在项目的pom.xml中添加依赖 2、编写二维码工具类 QRCodeUtil 3、生成图片二维码并保存

  • Java生成二维码

    1、添加依赖包 2、生成二维码图片的工具类 3、Controller 接口 4、Services 5、最后效果图 ...

网友评论

      本文标题:二维码生成工具类

      本文链接:https://www.haomeiwen.com/subject/ndoesktx.html