public static InputStream graphicsPoster(List<List<SetCharactersColVO>> rows) throws IOException {
final int w = 200;
final int h = 200;
//宽度
final int size = rows.size();
//计算高度
final int max = rows.parallelStream().map(List::size).max(Comparator.naturalOrder()).orElse(0);
OSS oss = getOssClient();
BufferedImage bi = new BufferedImage(size * w, max * w, BufferedImage.TYPE_4BYTE_ABGR);
Graphics2D graphics2D = bi.createGraphics();
//绘制白色背景
graphics2D.setColor(Color.WHITE);
graphics2D.fillRect(0, 0, size * w, max * w);
StringBuilder builder = new StringBuilder();
//边线 和 字体 之间的间隔
final int padding = 15;
for (int i = 0; i < size; i++) {
for (int j = 0, jSize = rows.get(i).size(); j < jSize; j++) {
final String img = rows.get(i).get(j).getCalligrapherCharacterImg();
if (Objects.nonNull(img)) {
//汉字图片
graphics2D.setColor(Color.BLACK);
graphics2D.drawRect(i * w + padding, j * h + padding, w - 2 * padding, h - 2 * padding);
builder.append(img);
BufferedImage image = ImageIO.read(oss.getObject(BUCKET_NAME, builder.substring(builder.lastIndexOf("images/"))).getObjectContent());
builder.delete(0, builder.length());
graphics2D.drawImage(image, i * w + 2 * padding, j * h + 2 * padding, w - 4 * padding, h - 4 * padding, null);
} else if (!StringUtils.isEmpty(rows.get(i).get(j).getChinese())) {
graphics2D.setColor(Color.BLACK);
graphics2D.drawRect(i * w + padding, j * h + padding, w - 2 * padding, h - 2 * padding);
//汉字
graphics2D.setFont(new Font("新宋体", Font.PLAIN, w - 4 * padding));
//汉字额外增加120 y值
graphics2D.drawString(rows.get(i).get(j).getChinese(), i * w + 2 * padding, j * h + 4 * padding + 100);
graphics2D.setPaint(new Color(255, 191, 0));
}
}
}
graphics2D.dispose();
//
// File file = new File("E://temp.png");
// ImageIO.write(bi, "png", file);
try(ByteArrayOutputStream bs = new ByteArrayOutputStream();
ImageOutputStream ios = ImageIO.createImageOutputStream(bs)) {
ImageIO.write(bi, "png", ios);
return new ByteArrayInputStream(bs.toByteArray());
}
// return null;
}
使用Graphics2D BufferedImage 动态生成图片
最新推荐文章于 2024-07-01 02:52:40 发布