发送图片而不是链接

9
我正在使用Microsoft Bot Framework和Cognitive Services来生成用户通过机器人上传的源图像。我使用的是C#语言。
Cognitive Services API返回一个代表处理后图像的byte[]Stream
如何直接将该图像发送给我的用户?所有文档和示例似乎都指向我必须将图像作为公共可访问的URL进行托管并发送链接。我可以这样做,但我不想这样做。
有没有人知道如何简单地返回图像,就像Caption Bot那样?
2个回答

9
您应该能够使用类似以下的内容:
var message = activity.CreateReply("");
message.Type = "message";

message.Attachments = new List<Attachment>();
var webClient = new WebClient();
byte[] imageBytes = webClient.DownloadData("https://placeholdit.imgix.net/~text?txtsize=35&txt=image-data&w=120&h=120");
string url = "data:image/png;base64," + Convert.ToBase64String(imageBytes)
message.Attachments.Add(new Attachment { ContentUrl = url, ContentType = "image/png" });
await _client.Conversations.ReplyToActivityAsync(message);

这在Web App Bot中可以工作,但在Microsoft Teams中会抛出错误... - jats
如果有人能解释一下这行代码的意思就太好了——string url = "data:image/png;base64," + Convert.ToBase64String(imageBytes)。这如何解决 OP 提出的问题? - Var

4
HTML图像元素的图像源可以是包含图像本身而不是用于下载图像的URL的数据URI。以下重载函数将接受任何有效图像并将其编码为可提供直接提供给HTML元素的src属性以显示图像的JPEG数据URI字符串。如果您预先知道返回的图像格式,则可以通过只返回已编码为Base 64的图像并带有适当的图像数据URI前缀来避免重新将图像编码为JPEG来节省一些处理时间。
    public string ImageToBase64(System.IO.Stream stream)
{
    // Create bitmap from stream
    using (System.Drawing.Bitmap bitmap = System.Drawing.Bitmap.FromStream(stream) as System.Drawing.Bitmap)
    {
        // Save to memory stream as jpeg to set known format.  Could also use PNG with changes to bitmap save 
        // and returned data prefix below
        byte[] outputBytes = null;
        using (System.IO.MemoryStream outputStream = new System.IO.MemoryStream())
        {
            bitmap.Save(outputStream, System.Drawing.Imaging.ImageFormat.Jpeg);
            outputBytes = outputStream.ToArray();
        }

        // Encoded image byte array and prepend proper prefix for image data. Result can be used as HTML image source directly
        string output = string.Format("data:image/jpeg;base64,{0}", Convert.ToBase64String(outputBytes));

        return output;
    }
}

public string ImageToBase64(byte[] bytes)
{
    using (System.IO.MemoryStream inputStream = new System.IO.MemoryStream())
    {
        inputStream.Write(bytes, 0, bytes.Length);
        return ImageToBase64(inputStream);
    }
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接