如何从azure java函数返回2d BuffereImage?

cwdobuhd  于 2021-06-29  发布在  Java
关注(0)|答案(1)|浏览(362)

在弄清楚如何从无服务器的azure函数返回缓冲映像时遇到问题。在google上找不到任何现有的例子。有人知道怎么做吗?

@FunctionName("HttpExample")
public HttpResponseMessage run(
        @HttpTrigger(
            name = "req",
            methods = {HttpMethod.GET, HttpMethod.POST},
            authLevel = AuthorizationLevel.ANONYMOUS)
            HttpRequestMessage<Optional<String>> request,
        final ExecutionContext context) {
    context.getLogger().info("Java HTTP trigger processed a request.");

    final Integer scale = Integer.parseInt(request.getQueryParameters().get("scale"));
    final String text = request.getQueryParameters().get("text");
    final String fillColor = request.getQueryParameters().get("fillColor");

    BufferedImage bufferedImage = new BufferedImage(30 * scale, 30 * scale, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2d = bufferedImage.createGraphics();

    g2d.setColor(Color.BLACK);
    g2d.fillRect(0, 0, 30 * scale, 30 * scale);

    g2d.setColor(Color.WHITE);
    g2d.setFont(new Font("Serif", Font.BOLD, 20));
    g2d.drawString(text, 10, 26);

    g2d.dispose();

    if (text == null || text.trim().length() == 0) {
        return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("Please pass the 3 required parameter names.").build();
    } else {
        OutputStream out = ??????
        return request.createResponseBuilder(HttpStatus.OK)
            .body(ImageIO.write(bufferedImage, "png", out))
            .build();
    }

}
fslejnso

fslejnso1#

我想出来了。仅返回原始字节[]:

} else {
        try {
        return request.createResponseBuilder(HttpStatus.OK)
            .header("Content-Type", "image/png")
            .body(toByteArray(bufferedImage, "png"))
            .build();
        } catch (IOException e) {
            return request.createResponseBuilder(HttpStatus.BAD_REQUEST).body("There was an error: " + e.getMessage()).build();
        }
    }

}

public static byte[] toByteArray(BufferedImage bi, String format) throws IOException {
    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    ImageIO.write(bi, format, baos);
    return baos.toByteArray();
}

我想知道有没有更好的办法做这件事。

相关问题