gpt4 book ai didi

java - 如何从 Azure Java 函数返回 2D BufferedImage?

转载 作者:行者123 更新时间:2023-12-03 03:53:58 24 4
gpt4 key购买 nike

无法弄清楚如何从无服务器 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();
}

}

最佳答案

我明白了。只需返回原始字节[]:

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

我想知道是否有更好的方法来做到这一点。

关于java - 如何从 Azure Java 函数返回 2D BufferedImage?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/65417688/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com