java实现【 生成小程序二维码:图片+二维码备注】

   1.逻辑:进行获取小程序的token进行-获取不限制的小程序码。
   2.参考的地址:
    微信官方文档:

官网-获取不限制的小程序码

  需要注意的点:
         1. 如果传入page这个参数的话必须定义check_path参数,不然无法识别-page指定的目录
         2. 如果设置字体上传服务器必须要有这个字体否则会乱码-
         		例如:微软雅黑
         在本机可在    C:\Windows   查看这个字体是否存在。

在这里插入图片描述

这个存在就可以使用,不会乱码

在这里插入图片描述

代码如下:

package com.kingsha.controller.pc;

import cn.hutool.extra.qrcode.QrCodeUtil;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.Map;

@Slf4j
public class TestNew {


    /**
     * 获取微信accesstoken
     *
     * @param wxappid
     * @param wxappkey
     * @return
     */
    public static String getWxAcesstoken(String wxappid, String wxappkey) throws CustomizeException {
        String tokenUrl = "https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=" + wxappid + "&secret=" + wxappkey;

        try {
            String jsonstr = HttpUtil.get(tokenUrl);
            JSONObject jsonObject = JSON.parseObject(jsonstr);
            if (jsonObject.containsKey("access_token")) {
                String accesstoken = jsonObject.getString("access_token");
                return accesstoken;
            } else {
                log.error("未获取到token");
                throw new CustomizeException("未获取到token");
            }

        } catch (Exception e) {
            log.error("未获取到token");
            throw new CustomizeException(e.getMessage());
        }
    }

    /*
     * 获取 二维码图片
   *
     */
    public static String getminiqrQr(HttpServletRequest request) {
        String p="E://a//新建文件夹"; //二维码生产的地址  本地F盘code文件夹
        String codeUrl=p+"/twoCode.png";
        String twoCodeUrl="twoCode.png";
        String appId ="";   //自己小程序的appid
        String secret ="";   //自己小程序的密钥
        try
        {
            //这里调用的是上面的获取access_token方法
            String access_token = getWxAcesstoken(appId, secret);
            URL url = new URL("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token="+access_token);
            HttpURLConnection httpURLConnection = (HttpURLConnection) url.openConnection();
            httpURLConnection.setRequestMethod("POST");// 提交模式
            // conn.setConnectTimeout(10000);//连接超时 单位毫秒
            // conn.setReadTimeout(2000);//读取超时 单位毫秒
            // 发送POST请求必须设置如下两行
            httpURLConnection.setDoOutput(true);
            httpURLConnection.setDoInput(true);
            // 获取URLConnection对象对应的输出流
//            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            // 发送请求参数
            JSONObject paramJson = new JSONObject();
//            id=2的数据
//                id 字段  status字段 0-未使用 1-已使用 time过期时间 create_time创建时间
            //第一次创建
            //1    0     2024-6-29     2024-6-28
            //1    1     2024-6-29     2024-6-28
            //过期时间进行对比
            paramJson.put("scene","2");//这就是你二维码里携带的参数 String型  名称不可变
            paramJson.put("page", "pages/product-list/index"); //这是设置扫描二维码后跳转的页面pages/home/home
            paramJson.put("width", 1280);//默认430,二维码的宽度,单位 px,最小 280px,最大 1280 px
            paramJson.put("is_hyaline", true);
            paramJson.put("check_path", false);
//            paramJson.put("auto_color", true);
            paramJson.put("env_version", "trial");//正式版为 "release",体验版为 "trial",开发版为 "develop"。默认是正式版。

            /**
             * TODO 新增部分开始 ---- 二维码中增加说明字段
             */
            // 发送请求
            PrintWriter printWriter = new PrintWriter(httpURLConnection.getOutputStream());
            printWriter.write(paramJson.toString());
            printWriter.flush();
            // 获取二维码图片流并保存
            BufferedInputStream bis = new BufferedInputStream(httpURLConnection.getInputStream());
            OutputStream os = new FileOutputStream(new File(codeUrl));
            int len;
            byte[] arr = new byte[1024];
            while ((len = bis.read(arr)) != -1) {
                os.write(arr, 0, len);
                os.flush();
            }
            os.close();
            // 在生成的二维码图片下方添加文字
            BufferedImage qrCodeImage = ImageIO.read(new File(codeUrl)); // 读取已生成的二维码图片
            //设置名称
            String text = "机构1";
            //字体的大小
            int fontSize = 150;
            //二维码的大小 - 值越大图片越小
            int extraSpaceBelowText = 200;
            BufferedImage imageWithText = new BufferedImage(qrCodeImage.getWidth(), 		qrCodeImage.getHeight() + fontSize + extraSpaceBelowText, BufferedImage.TYPE_INT_ARGB);
            Graphics2D g2d = imageWithText.createGraphics();
            g2d.drawImage(qrCodeImage, 0, 0, null);

            Font font = new Font("微软雅黑", Font.PLAIN, fontSize);
            FontMetrics fontMetrics = g2d.getFontMetrics(font);
            int textWidth = fontMetrics.stringWidth(text);
            int x = (qrCodeImage.getWidth() - textWidth) / 2;
            int y = qrCodeImage.getHeight() + fontSize;

            g2d.setColor(Color.BLACK);
            g2d.setFont(font);
            g2d.drawString(text, x, y);

            g2d.dispose();

            // 保存带有文字的二维码图片
            File outputfile = new File(p + "/twoCode_with_text.png");
            ImageIO.write(imageWithText, "png", outputfile);

            return outputfile.getName(); // 返回生成的带文字的二维码图片文件名



        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        return twoCodeUrl;
    }


    public static void main(String[] args) {
        JSONObject data=new JSONObject();
        data.put("twoCodeUrl", getminiqrQr(null));

        System.out.println(data);
    }

}

实现的效果:
在这里插入图片描述

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值