2

I want to display a QR Code picture back to the client.

Here is my code in 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);
}

I'm not really sure how to reply an image object as an attachment though..

Thank you very much!

Tony Lu
  • 25
  • 1
  • 4
  • Possible duplicate of [Send an image rather than a link](https://stackoverflow.com/questions/39246174/send-an-image-rather-than-a-link) – Ezequiel Jadib Oct 25 '17 at 10:38

1 Answers1

3

You just need a few steps between your QRCode encode and the attachment content: convert the Bitmap to a byte[], then convert to base64 and add it as 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);

Demo:

Demo

Nicolas R
  • 13,812
  • 2
  • 28
  • 57