【问题标题】:Send an image rather than a link发送图片而不是链接
【发布时间】:2017-01-07 20:11:35
【问题描述】:

我正在使用带有认知服务的 Microsoft Bot Framework 从用户通过机器人上传的源图像生成图像。我正在使用 C#。

认知服务 API 返回代表处理后图像的 byte[]Stream

如何将该图像直接发送给我的用户?所有文档和示例似乎都指向我必须将图像托管为可公开寻址的 URL 并发送链接。我可以这样做,但我不想这样做。

有谁知道如何像 Caption Bot 那样简单地返回图像?

【问题讨论】:

    标签: botframework microsoft-cognitive skype-bots


    【解决方案1】:

    HTML 图像元素的图像源可以是直接包含图像的数据 URI,而不是用于下载图像的 URL。以下重载函数将获取任何有效图像并将其编码为 JPEG 数据 URI 字符串,该字符串可直接提供给 HTML 元素的 src 属性以显示图像。如果您提前知道返回的图像格式,那么您可以通过返回带有适当图像数据 URI 前缀的 base 64 编码的图像而不将图像重新编码为 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);
        }
    }
    

    【讨论】:

      【解决方案2】:

      你应该可以使用这样的东西:

      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 团队中引发错误...
      • 如果有人解释这一行是什么意思,那就太好了 -- string url = "data:image/png;base64," + Convert.ToBase64String(imageBytes) 如何解决这个问题OP问。
      猜你喜欢
      • 2011-04-08
      • 2011-04-16
      • 1970-01-01
      • 2017-01-27
      • 1970-01-01
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多