返回微信小程序码图片流的工具类
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import javax.imageio.ImageIO;
import org.apache.http.HttpResponse;
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.HttpClientBuilder;
import org.apache.http.protocol.HTTP;
import com.alibaba.fastjson.JSON;
public class QRcodeUtil {
/**
* 生成指定尺寸小程序码
*
* @param sceneStr (参数)
* @param accessToken (凭证)
* @param page (扫码跳转页面)
* @param width (小程序码大小)
* @return 返回一个图片流
*/
public static BufferedImage generatedQrImg(String sceneStr, String accessToken, String page, Integer width) {
Map<String, Object> params = new HashMap<>(3);
//参数
params.put("scene", sceneStr);
//要跳转的页面
params.put("page", page);
//二维码宽度 如果小于默认参数 使用微信最小参数280
params.put("width", width < 280 ? 280 : width);
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
HttpPost httpPost = new HttpPost("https://api.weixin.qq.com/wxa/getwxacodeunlimit?access_token=" + accessToken);
httpPost.addHeader(HTTP.CONTENT_TYPE, "application/json");
String body = JSON.toJSONString(params);
try {
StringEntity entity = new StringEntity(body);
entity.setContentType("image/png");
httpPost.setEntity(entity);
HttpResponse response = httpClient.execute(httpPost);
InputStream inputStream = response.getEntity().getContent();
//字节流转图片对象
Image image = ImageIO.read(inputStream);
//构建新图片
BufferedImage tag = new BufferedImage(width, width, BufferedImage.TYPE_INT_RGB);
tag.getGraphics().drawImage(image , 0, 0, 165, 165, null);
return tag;
} catch (Exception e) {
System.out.println(e.getMessage());
}
return null;
}
}