在 Bot framework 上回复二维码 MessagingToolkit.QRCode

Reply QR Code on Bot framework with MessagingToolkit.QRCode

我想显示一个二维码图片返回给客户端。

这是我在 RootDialog 中的代码,

[LuisIntent("None")]
[LuisIntent("")]
public async Task None(IDialogContext context, LuisResult result)
{
    string qrText = "Photo";
    QRCodeEncoder enc = new QRCodeEncoder();
    Bitmap qrcode = enc.Encode(qrText);

    var message = context.MakeMessage();
    Attachment attachment = new Attachment();
    attachment.ContentType = "image/jpg";
    attachment.Content = qrcode as Image; // This line is not sure...
    attachment.Name = "Image";
    message.Attachments.Add(attachment);
    await context.PostAsync(message);
}

虽然我不太确定如何将图像对象作为附件回复..

非常感谢!

您只需在 QRCode encode 和附件内容之间进行几步操作:将 Bitmap 转换为 byte[],然后转换为 base64 并将其添加为 ContentUrl:

string qrText = "Photo";
QRCodeEncoder enc = new QRCodeEncoder();
Bitmap qrcode = enc.Encode(qrText);

// Convert the Bitmap to byte[]
System.IO.MemoryStream stream = new System.IO.MemoryStream();
qrcode.Save(stream, System.Drawing.Imaging.ImageFormat.Bmp);
byte[] imageBytes = stream.ToArray();

var message = context.MakeMessage();
Attachment attachment = new Attachment
{
    ContentType = "image/jpg",
    ContentUrl = "data:image/jpg;base64," + Convert.ToBase64String(imageBytes),
    Name = "Image.jpg"
};
message.Attachments.Add(attachment);
await context.PostAsync(message);

演示: