2.3 QrcodeUtils.java
2.3.1 获取背景
注意以下代码中的第一行代码。
InputStream inputStream = Thread.currentThread().getContextClassLoader()
.getResourceAsStream(config.getBgFile());
File bgFile = Files.createTempFile("bg_", ".jpg").toFile();
FileUtils.copyInputStreamToFile(inputStream, bgFile);
2.3.2 获取微信头像
通过建立HttpGet请求来获取微信头像。
CloseableHttpClient httpclient = HttpClientBuilder.create().build(); HttpGet httpget = new HttpGet(config.getHeadimgUrl()); httpget.addHeader("Content-Type", "text/html;charset=UTF-8"); // 配置请求的超时设置 RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(500) .setConnectTimeout(500).setSocketTimeout(500).build(); httpget.setConfig(requestConfig); try (CloseableHttpResponse response = httpclient.execute(httpget); InputStream headimgStream = handleResponse(response);) { Header[] contentTypeHeader = response.getHeaders("Content-Type"); if (contentTypeHeader != null && contentTypeHeader.length > 0) { if (contentTypeHeader[0].getValue().startsWith(ContentType.APPLICATION_JSON.getMimeType())) { // application/json; encoding=utf-8 下载媒体文件出错 String responseContent = handleUTF8Response(response); logger.warn("下载网络头像出错{}", responseContent); } } headimgFile = createTmpFile(headimgStream, "headimg_" + UUID.randomUUID(), "jpg"); } catch (Exception e) { logger.error(e.getMessage(), e); throw new Exception("头像文件读取有误!", e); } finally { httpget.releaseConnection(); }
通过createTmpFile方法将图像下载到本地。
public static File createTmpFile(InputStream inputStream, String name, String ext) throws IOException {
File tmpFile = File.createTempFile(name, '.' + ext);
tmpFile.deleteOnExit();
try (FileOutputStream fos = new FileOutputStream(tmpFile)) {
int read = 0;
byte[] bytes = new byte[1024 * 100];
while ((read = inputStream.read(bytes)) != -1) {
fos.write(bytes, 0, read);
}
fos.flush();
return tmpFile;
}
}
2.3.3 在背景图上绘制二维码、头像、昵称
private static void increasingImage(BufferedImage image, String format, String imagePath, File bgFile, MatrixToBgImageConfig config, File headimgFile) throws Exception { try { BufferedImage bg = ImageIO.read(bgFile); Graphics2D g = bg.createGraphics(); // 二维码的高度和宽度如何定义 int width = config.getQrcode_height(); int height = config.getQrcode_height(); // logo起始位置,此目的是为logo居中显示 int x = config.getQrcode_x(); int y = config.getQrcode_y(); // 绘制图 g.drawImage(image, x, y, width, height, null); BufferedImage headimg = ImageIO.read(headimgFile); int headimg_width = config.getHeadimg_height(); int headimg_height = config.getHeadimg_height(); int headimg_x = config.getHeadimg_x(); int headimg_y = config.getHeadimg_y(); // 绘制头像 g.drawImage(headimg, headimg_x, headimg_y, headimg_width, headimg_height, null); // 绘制文字 g.setColor(Color.GRAY);// 文字颜色 Font font = new Font("宋体", Font.BOLD, 28); g.setFont(font); g.drawString(config.getRealname(), config.getRealname_x(), config.getRealname_y()); g.dispose(); // 写入二维码到bg图片 ImageIO.write(bg, format, new File(imagePath)); } catch (Exception e) { throw new Exception("二维码添加bg时发生异常!", e); } }