多文件压缩包
生成二维码 并且在二维码图片上添加提示信息 , 批量二维码创建时 支持打包zip格式
/**
* 生成二维码图片
*
* @param content 二维码携带的内容
* @param pressText 需要在二维码图片上添加的内容
*/
public static BufferedImage createQRCodePicture(String content, String pressText) {
Map<EncodeHintType, Object> hints = new HashMap<>();
hints.put(EncodeHintType.CHARACTER_SET, "UTF-8");
hints.put(EncodeHintType.MARGIN, 0);
int onColor = 0xFF000000; //前景色
int offColor = 0xBFB0A8; //背景色
int width = 430; //大小
try {
MatrixToImageConfig config = new MatrixToImageConfig(onColor, offColor);
BitMatrix bitMatrix = new MultiFormatWriter()
.encode(content, BarcodeFormat.QR_CODE, width, width, hints);
BufferedImage image = MatrixToImageWriter.toBufferedImage(bitMatrix, config);
int fontSize = Double.valueOf(image.getHeight() * 0.1).intValue();
BufferedImage resultImage = pressText(String.valueOf(pressText), image, fontSize);
return resultImage;
} catch (Exception e) {
log.error("二维码创建失败:" + e.getMessage());
}
return null;
}
/**
* 在绘制的二维码上面添加文字信息.
*
* @param pressText 在图片上插入的内容
* @param src 二维码图片
* @param fontSize 字体大小
* @return {@link BufferedImage}
*/
public static BufferedImage pressText(String pressText, BufferedImage src, int fontSize) {
try {
BufferedImage outImage = new BufferedImage(src.getWidth(), src.getHeight() + fontSize,
BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D g2 = outImage.createGraphics();
//把二维码重新在新的画板上绘制
g2.drawImage(src, 0, 0, src.getWidth(), src.getHeight(), null);
g2.setColor(Color.BLACK);
g2.setFont(new Font(Font.SERIF, Font.BOLD, fontSize));
int stringWidth = g2.getFontMetrics().stringWidth(pressText);
//绘制文字信息
int fontY = Double.valueOf(fontSize * 0.9).intValue();
g2.drawString(pressText, (src.getWidth() - stringWidth) / 2,
src.getHeight() + fontY);
outImage.flush();
g2.dispose();
return outImage;
} catch (Exception e) {
log.error("二维码图片上添加信息失败:" + e.getMessage());
}
return null;
}
public void createBatchByZip(HttpServletResponse httpServletResponse) {
ZipOutputStream zout = null;
try {
zout = new ZipOutputStream(httpServletResponse.getOutputStream());
Map<Integer, BufferedImage> resultMap = queryMallQrcodeList();
if (CollectionUtils.isEmpty(resultMap)) {
return;
}
for (Integer key : resultMap.keySet()) {
BufferedImage bufferedImage = resultMap.get(key);
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ImageIO.write(bufferedImage, "png", baos);
ZipEntry zipEntry = new ZipEntry(key + ".png");
zout.putNextEntry(zipEntry);
zout.write(baos.toByteArray());
zout.closeEntry();
zout.flush();
}
} catch (Exception e) {
log.error("二维码压缩包失败", e.getMessage());
} finally {
try {
if (null != zout) {
zout.flush();
zout.close();
}
} catch (IOException e) {
log.error("二维码压缩包失败", e.getMessage());
}
}
}