将我的图像从 MS Graph 显示到 Azure 机器人服务

Display my image from MS Graph to Azure Bot Services

如何向用户发送一张卡片,其中包含我从 Microsoft Graph 收到的照片,例如 url https://graph.microsoft.com/v1.0/me/photo/$value?我认为它 returns 是一个 blob,但机器人框架需要一个图像 url 来代替。我用 CardFactory.heroCard(..., [photo], ...) 试过了,但没有显示。

documentation 描述了如何在消息中包含内联图像二进制文件:

For channels that support inline binaries of an image, you can set the contentUrl property of the Attachment to a base64 binary of the image (for example, data:image/png;base64,iVBORw0KGgo…). The channel will display the image or the image's URL next to the message's text string.

在 BotBuilder V4 Node SDK 中,您可以像这样将图像二进制文件转换为 base64:

// After getting an HTTP response:

var imageType = "image/jpeg"
var imageBytes = Buffer.from(response.data).toString('base64');
var imageSrc = `data:${imageType};base64,${imageBytes}`;

var reply = MessageFactory.attachment({
    contentType: imageType,
    contentUrl: imageSrc,
    name: "Your photo"
}, "Here it is:");

await turnContext.sendActivity(reply);

有一个问题需要牢记。如果您使用的是 Axios 库(这是一个好主意,因为它可以让您等待 HTTP 请求), 否则图像二进制文件的格式可能不正确,图像将无法呈现:

var response = await axios.get("https://graph.microsoft.com/v1.0/me/photo/$value", {
    responseType: 'arraybuffer'
});