使用Graphics2D BufferedImage 动态生成图片

  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;
    }

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

等一场春雨

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值