java生成二维码

java生成二维码
效果预览:
在这里插入图片描述在这里插入图片描述
简单记录!

1、jar包

<!--二维码依赖包-->
        <!-- https://mvnrepository.com/artifact/com.google.zxing/core -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.4.0</version>
        </dependency>
        <!-- https://mvnrepository.com/artifact/com.google.zxing/javase -->
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>javase</artifactId>
            <version>3.4.0</version>
        </dependency>

2、生成二维码类

public class QRcodePrintUtil {

    private static final String CHARSET = "utf-8";
    // LOGO宽度
    private static final int WIDTH = 80;
    // LOGO高度
    private static final int HEIGHT = 80;


    /**
     * 格式化展示数据 ,每行限制最大字
     * @param listData
     * @param content
     * @param imgPath
     * @param needCompress
     * @throws Exception
     */
    public static BufferedImage formatCreateImage(Integer strSize,List<String> listData, String content, String imgPath, boolean needCompress,Integer qrcodeSize,Integer canvasWidth,Integer canvasHeight,Integer imageX,Integer imageY,String fontName,Integer fontSize,Integer oneY) throws Exception {

        List<String> list = new ArrayList<>();

//      每行限制 11位字,防止打印出边界
        if(CollectionUtils.isNotEmpty(listData)){

            for (String str : listData){

                int maxStr = str.length()/strSize;
                if((str.length()%strSize)!=0){
                    maxStr = maxStr+1;
                }
                for (int i=0;i<maxStr;i++){
                    if(i==maxStr-1){
                        list.add(str.substring(i*strSize));
                    }else {
                        list.add(str.substring(i*strSize,i*strSize+strSize));
                    }

                }
            }
        }

        return createImage( list,  content,  imgPath,  needCompress, qrcodeSize, canvasWidth, canvasHeight, imageX, imageY, fontName, fontSize, oneY);
    }

    /**
     * 创建图片
     * @param code          文本内容
     * @param content     二维码内容
     * @param imgPath      Logo图标地址
     * @param needCompress   是否需要缩小logo图标
     * @param canvasWidth   画布宽
     * @param canvasHeight  画布高
     * @param imageX    二维码 起始点 X
     * @param imageY    二维码 起始点 Y
     * @param fontName   字体名称: 微软雅黑
     * @param fontSize  字体大小
     * @param oneY  text 行间距
     * @return
     * @throws Exception
     */
    private static BufferedImage createImage(List<String> code, String content, String imgPath, boolean needCompress,Integer qrcodeSize,Integer canvasWidth,Integer canvasHeight,Integer imageX,Integer imageY,String fontName,Integer fontSize,Integer oneY) throws Exception {
        Map<EncodeHintType, Object> hints = new Hashtable<>();
        hints.put(EncodeHintType.ERROR_CORRECTION, ErrorCorrectionLevel.H);
        hints.put(EncodeHintType.CHARACTER_SET, CHARSET);
        hints.put(EncodeHintType.MARGIN, 1);
        BitMatrix bitMatrix = new MultiFormatWriter().encode(content, BarcodeFormat.QR_CODE, qrcodeSize, qrcodeSize,hints);
        int width = bitMatrix.getWidth();
        int height = bitMatrix.getHeight();
        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        for (int x = 0; x < width; x++) {
            for (int y = 0; y < height; y++) {
                image.setRGB(x, y, bitMatrix.get(x, y) ? 0xFF000000 : 0xFFFFFFFF);
            }
        }

        //在二维码下方增加文字显示
//        BufferedImage bi = new BufferedImage(width, height+20*code.size(), BufferedImage.TYPE_INT_RGB);//将高度增加20,在二维码下方增加一个区域显示文字

        BufferedImage bi = new BufferedImage(canvasWidth, canvasHeight, BufferedImage.TYPE_INT_RGB);
        Graphics2D g2 = bi.createGraphics();
        g2.setBackground(new Color(0xFF,0xFF,0xFF));
//        g2.clearRect(0, 0, width, height);
        g2.clearRect(0, 0, canvasWidth, canvasHeight);

        g2.drawImage(image, imageX, imageY, width, height, null); //x,y为image图片的位置
        //设置生成图片的文字样式
        Font font = new Font(fontName, Font.BOLD, fontSize);
        g2.setFont(font);
        g2.setPaint(new Color(0x0,0x0,0x0));


        Integer firstY = (canvasHeight-oneY)/code.size()+(canvasHeight-oneY)/code.size()/2;

        // 设置字体在图片中的位置 在这里是居中
        for(int i=0;i<code.size();i++){
            // 防止生成的文字带有锯齿
            g2.setRenderingHint(RenderingHints.KEY_TEXT_ANTIALIASING, RenderingHints.VALUE_TEXT_ANTIALIAS_ON);

            // 在图片上生成文字
            g2.drawString(code.get(i), imageX+width, firstY); //x,y为文字的位置
            firstY = firstY + oneY;

        }

        image=bi;
        if (imgPath == null || "".equals(imgPath))
            return image;
        // 插入图片
        QRcodePrintUtil.insertImage(qrcodeSize,image, imgPath, needCompress, code);
        return image;
    }

    /**
     * 插入logo图标
     * @param source 二维码Image对象
     * @param imgPath logo路径
     * @param needCompress 是否需要缩小logo图标
     * @param code
     * @throws Exception
     */
    private static void insertImage(Integer qrcodeSize,BufferedImage source, String imgPath, boolean needCompress, List<String> code) throws Exception {
        File file = new File(imgPath);
        if (!file.exists()) {
            System.err.println("" + imgPath + "该文件不存在!");
            return;
        }
        Image src = ImageIO.read(new File(imgPath));
        int width = src.getWidth(null);
        int height = src.getHeight(null);
//        if (needCompress) { // 压缩LOGO
        if(StringUtils.isNotBlank(imgPath)){
            if (width > WIDTH) {
                width = WIDTH;
            }
            if (height > HEIGHT) {
                height = HEIGHT;
            }
            BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
            Graphics g = image.getGraphics();
            g.drawImage(src, 0, 0, width, height, null); // 绘制图
            // 画边框
            g.setColor(Color.BLACK);
            g.drawRect(4, 4, width - 8, height - 8);
            g.drawRect(5, 5, width - 10, height - 10);

            g.dispose();
            src = image;
        }
        // 插入LOGO
        Graphics2D graph = source.createGraphics();
        int x = (qrcodeSize - width) / 2;
        int y = (qrcodeSize - height) / 2;
        graph.drawImage(src, x, y+code.size()*20, width, height, null);//logo的位置可能需要调整
        Shape shape = new RoundRectangle2D.Float(x, y+code.size()*20, width, width, 6, 6);//阴影的位置可能需要调整
        graph.setStroke(new BasicStroke(3f));
        graph.draw(shape);
        graph.dispose();
    }

    /**
     * 生成包含logo的二维码
     * @param code 需要显示在二维码上方的list文字集合
     * @param content 二维码中包含的内容
     * @param imgPath logo图像地址
     * @param needCompress 是否需要缩小logo图标
     * @param fileUtil 保存文件的类对象
     * @return 保存后的文件路径
     * @throws Exception
     */
    public static String encode(Integer strSize,List<String> code, String content,String filesPath, String imgPath, boolean needCompress, QRcodeFilesUtil fileUtil,Integer qrcodeSize,Integer canvasWidth,Integer canvasHeight,Integer imageX,Integer imageY,String fontName,Integer fontSize,Integer oneY) throws Exception {
        BufferedImage image = QRcodePrintUtil.formatCreateImage( strSize, code,  content,  imgPath,  needCompress, qrcodeSize, canvasWidth, canvasHeight, imageX, imageY, fontName, fontSize, oneY);
        //获取当前时间并格式化
        String path=new SimpleDateFormat("yyyy/MM/dd hh:mm:ss").format(new Date());
        path=path.substring(0,10);
        //保存文件到磁盘
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        ImageIO.write(image, "png", os);
        InputStream input = new ByteArrayInputStream(os.toByteArray());
        return fileUtil.writeFile(input, filesPath+path, path+".png");
    }


    public static String encode(List<String> code, String content,String filesPath,  QRcodeFilesUtil fileUtil) throws Exception {
        return QRcodePrintUtil.encode( code,  content, filesPath, null,fileUtil);
    }

    public static String encode(List<String> code, String content,String filesPath, String imgPath, QRcodeFilesUtil fileUtil) throws Exception {
        return QRcodePrintUtil.encode( code,  content, filesPath, imgPath,fileUtil, 550);
    }


    public static String encode(List<String> code, String content,String filesPath, String imgPath, QRcodeFilesUtil fileUtil,Integer qrcodeSize) throws Exception {
        return QRcodePrintUtil.encode( code,  content, filesPath, imgPath, fileUtil, qrcodeSize,1);
    }


    public static String encode(List<String> code, String content,String filesPath, String imgPath, QRcodeFilesUtil fileUtil,Integer qrcodeSize,Integer doubleNum) throws Exception {
        return QRcodePrintUtil.encode( code,  content, filesPath, imgPath, fileUtil, qrcodeSize,doubleNum,1200,800,50,100);
    }


    public static String encode(List<String> code, String content,String filesPath, String imgPath, QRcodeFilesUtil fileUtil,Integer qrcodeSize,Integer doubleNum,Integer canvasWidth,Integer canvasHeight,Integer imageX,Integer imageY) throws Exception {
        return QRcodePrintUtil.encode(code, content, filesPath, imgPath, fileUtil,qrcodeSize, doubleNum,canvasWidth,  canvasHeight, imageX, imageY, "微软雅黑", 54, 100);
    }


    public static String encode(List<String> code, String content,String filesPath,String imgPath,   QRcodeFilesUtil fileUtil,Integer qrcodeSize,Integer doubleNum,Integer canvasWidth,Integer canvasHeight,Integer imageX,Integer imageY,String fontName,Integer fontSize,Integer oneY) throws Exception {
        return QRcodePrintUtil.encode(  code,  content, filesPath,  imgPath,  false,  fileUtil,qrcodeSize, doubleNum,canvasWidth, canvasHeight, imageX, imageY, fontName, fontSize, oneY);
    }

    public static String encode(List<String> code, String content,String filesPath, String imgPath, boolean needCompress, QRcodeFilesUtil fileUtil,Integer qrcodeSize,Integer doubleNum,Integer canvasWidth,Integer canvasHeight,Integer imageX,Integer imageY,String fontName,Integer fontSize,Integer oneY) throws Exception {
        return QRcodePrintUtil.encode( 11,code,  content, filesPath,  imgPath,  needCompress,  fileUtil,qrcodeSize*doubleNum, canvasWidth*doubleNum, canvasHeight*doubleNum, imageX*doubleNum, imageY*doubleNum, fontName, fontSize*doubleNum, oneY*doubleNum);
    }
}

3、文件类

public class QRcodeFilesUtil {

    /**
     * 保存文件对象
     * @throws IOException
     */
    public String writeFile(InputStream input, String path, String fileName) throws IOException {
        fileName=System.currentTimeMillis()+fileName.substring(fileName.indexOf("."));
        String filePath = verifyFolderExist(null, path, fileName);
        if (filePath == null) return filePath;
        writeFile(input, new File(filePath));
        return path + File.separator + fileName;
    }
    /**
     * 校验文件夹path文件夹是否存在
     * @param file
     * @param path
     * @param fileName
     * @return
     */
    public String verifyFolderExist(File file, String path, String fileName) {
        String folder_path = path;
        String filePath = folder_path + File.separator + fileName;
        if (file != null && file.getAbsolutePath().equals(filePath)) {
            return null;
        }
        File folder = new File(folder_path);
        if (!folder.exists()) {
            folder.mkdirs();
        }
        return filePath;
    }
    /**
     * 写入文件
     * @param is
     * @param target
     * @throws IOException
     */
    public void writeFile(InputStream is, File target) throws IOException {
        OutputStream os = new FileOutputStream(target);
        byte[] bytes = new byte[1024 * 1024];
        int len = 0;
        while ((len = is.read(bytes, 0, bytes.length)) > 0) {
            os.write(bytes, 0, len);
        }
        is.close();
        os.close();
    }

}

4、测试类

public class PrintLabelMain {

    public static void main(String[] args){

        List<String> list = new ArrayList<>();
        list.add("单位:单位名称");
        list.add("设备类型:设备名称");
        list.add("编号:E0005");
        list.add("位置:几号楼几单元几零几室");

        try {
        //无logo的二维码
            String path = new QRcodePrintUtil().encode(list, "这是二维码中的内容", "I:\\/qrcode/",new QRcodeFilesUtil());
              
        //有logo的二维码
            String path1 = new QRcodePrintUtil().encode(list, "这是二维码中的内容", "I:\\/qrcode/","I:\\/qrcode/1.jpg",new QRcodeFilesUtil());
            
        }catch (Exception e){
            System.out.println(e);
        }

}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值