有时候咱们可能须要在其余的网页上展现咱们本身的小程序中某些页面的小程序码,这种时候,咱们须要用到小程序的生成小程序码的相关接口。
工具选型
项目配置
生成小程序码的相关类型
- 小程序码的其余生成方式以及相关类型在这篇文章点此进入中介绍的较为详细,此处再也不赘述,如下仅以生成不限制张数的这种类型来作一个示例。
生成小程序码图片
- 先获取小程序的service实例wxMaService。
- 再获取二维码相关操做的service实例
// 获取小程序服务实例
WxMaService wxMaService = WxMaConfiguration.getWxMaService();
// 获取小程序二维码生成实例
WxMaQrcodeService wxMaQrcodeService = wxMaService.getQrcodeService();
// 设置小程序二维码线条颜色为黑色
WxMaCodeLineColor lineColor = new WxMaCodeLineColor("0", "0", "0");
// 生成二维码图片字节流(此处也能够生成File类型,若是想将图片文件保存到服务器就生成File类型,此处生成byte[]类型,方便直接返回文件流到前端)
byte[] qrCodeBytes = null;
qrCodeBytes = wxMaQrcodeService.createWxaCodeUnlimitBytes(String.valueOf(id), null, 430, false, lineColor, false);
返回文件流
- 将文件流写到response中,相关示例代码以下:
@RestController
@RequestMapping("/qrCode")
public class QrCodeController {
private static final Logger logger = LoggerFactory.getLogger(QrCodeController.class);
@GetMapping("/getMiniappQrCode/{id}")
public void getMiniappQrCode(@PathVariable("id") Long id, HttpServletRequest request, HttpServletResponse response) throws Exception{
// 获取小程序服务实例
WxMaService wxMaService = WxMaConfiguration.getWxMaService();
// 获取小程序二维码生成实例
WxMaQrcodeService wxMaQrcodeService = wxMaService.getQrcodeService();
// 设置小程序二维码线条颜色为黑色
WxMaCodeLineColor lineColor = new WxMaCodeLineColor("0", "0", "0");
// 生成二维码图片字节流
byte[] qrCodeBytes = null;
try{
qrCodeBytes = wxMaQrcodeService.createWxaCodeUnlimitBytes(String.valueOf(id), null, 430, false, lineColor, false);
} catch(Exception e){
logger.error("生成小程序码出错", e);
}
// 设置contentType
response.setContentType("image/png");
// 写入response的输出流中
OutputStream stream = response.getOutputStream();
stream.write(qrCodeBytes);
stream.flush();
stream.close();
}
}
Diboot - 简单高效的轻代码开发框架前端