【问题标题】:Microsoft Cognitive Services Vision API: Sending multipart dataMicrosoft Cognitive Services Vision API:发送多部分数据
【发布时间】:2017-08-30 22:51:47
【问题描述】:

我试图通过根据文档传递多个图像并使用multipart/form-data 来调用 Microsoft Cognitive API,但我收到一条错误消息,显示“不支持的媒体类型”。我尝试同时使用ByteArrayStreamContent

Api documentation.

private static byte[] GetImageAsByteArray(Stream fileStream)
{
    using (var binaryReader = new BinaryReader(fileStream))
    {
        return binaryReader.ReadBytes((int)fileStream.Length);
    }
}

static void Main(string[] args)
{
    var uriBase = "https://westus.api.cognitive.microsoft.com/vision/v1.0/recognizeText";
    var subscriptionKey = "<subscriptionKey>";
    var client = new HttpClient();
    var uri = string.Concat(uriBase, "?", "language=en&detectOrientation=true");
    var images = new List<Stream>();
    var img = Image.FromStream(File.Open("<imageName>", FileMode.Open));
    var stream = new MemoryStream();

    img.Save(stream, ImageFormat.Bmp);
    stream.Position = 0;

    images.Add(stream);

    using (var content = new MultipartFormDataContent())
    {
        foreach (var image in images)
        {
            //content.Add(new StreamContent(stream));
            content.Add(new ByteArrayContent(GetImageAsByteArray(image)));
        }

        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", subscriptionKey);
        content.Headers.ContentType = new MediaTypeHeaderValue("multipart/form-data");

        var response = client.PostAsync(uri, content).Result;
    }
}

【问题讨论】:

  • passing multiple images as per documentation? api 文档并没有说你可以传入多个图像...
  • 感谢您的回复,但在这种情况下,multipart/form-data 不是用于上传多个值的图像吗?也许这对我来说是一个糟糕的假设,但他们为什么要支持 multipart/form-data?

标签: c# microsoft-cognitive


【解决方案1】:

我试图通过根据文档传递多个图像并使用 multipart/form-data 来调用 Microsoft Cognitive API,但我收到一条错误消息,显示“不支持的媒体类型”。

It is not possible to send multiple images, regardless of header.

请参考documentation Step 2,里面提到:

执行计算机视觉 API 调用的基本方法是直接上传图像。这是通过发送具有 application/octet-stream 内容类型的 "POST" 请求以及从 图像 读取的数据来完成的。 p>

示例代码可见here

测试环境here。 请注意,无论标题如何,它仍在发送 1 张图像。 限制还提到了单个图像。

【讨论】:

  • 感谢您的回答,但我已经可以发送一张图片了。我更感兴趣的是如何使用 multipart/form-data: ' // 此示例使用内容类型“application/octet-stream”。 // 您可以使用的其他内容类型是“application/json”和“multipart/form-data”。'
  • 更新了答案。
  • 问题比较模糊,部分原因是某些 Microsoft 认知服务 API 方法接受多部分 MIME,而其他方法则不接受。例如/ocr 可以,但/recognizeText 不会。另请注意,支持多部分 MIME 的任何方法都不会处理除第一部分之外的任何内容,不支持在单个请求中处理多个图像。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-12-01
  • 1970-01-01
  • 2018-09-22
  • 2021-12-19
  • 1970-01-01
  • 2017-11-03
  • 2016-10-24
相关资源
最近更新 更多