0

我正在尝试使用Microsoft 的 FaceAPI从图片中获取 JSON 数据。我收到了一个 StatusCode OK,但没有得到任何重要的回报。我已经通过将 MemoryStream 保存到文件中验证了 MemoryStream 具有正确的数据(我从 Image 控件中获取)。

    private async Task<string> GetJSON()
    {
        var client = new HttpClient();
        var queryString = HttpUtility.ParseQueryString(string.Empty);

        // Request headers
        client.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "mykey");

        // Request parameters
        queryString["returnFaceId"] = "true";
        queryString["returnFaceLandmarks"] = "false";
        var uri = "https://api.projectoxford.ai/face/v1.0/detect?" + queryString;

        HttpResponseMessage response;

        // Request body
        byte[] byteData = ImageToByte();


        using (var content = new ByteArrayContent(byteData))
        {
            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            response = await client.PostAsync(uri, content);
        }

        return "";
    }

    private byte[] ImageToByte()
    {
        using (MemoryStream stream = new MemoryStream())
        {
            videoBox.Dispatcher.Invoke(delegate
            {
                var encoder = new PngBitmapEncoder();

                var flippedBitmap = new TransformedBitmap();
                flippedBitmap.BeginInit();
                flippedBitmap.Source = (BitmapSource)videoBox.Source;
                var transform = new ScaleTransform(-1, 1);
                flippedBitmap.Transform = transform;
                flippedBitmap.EndInit();
                encoder.Frames.Add(BitmapFrame.Create(flippedBitmap));
                encoder.Save(stream);

            });

            using (FileStream test = new FileStream("snapshot.bmp", FileMode.Create))
            {
                stream.Position = 0;
                stream.CopyTo(test);
            }

            return stream.ToArray();
        }
    }
4

2 回答 2

1

您需要调用await response.Content.ReadAsStringAsync()以获取 JSON。

或者,您可以使用 Microsoft.ProjectOxford.Face NuGet 包,它为您完成管道,并提供 C# 类型,从而减轻您解析 JSON 的乏味。

于 2016-06-20T02:54:40.973 回答
0

我不是 ac# 程序员,但在查看您的代码后,方法 GetJSON 正在返回硬编码的空字符串,这可能是您在调用此方法后没有从服务器返回任何内容的原因,或者第二个原因可能是您的异步​​服务器配置不是正常工作,因此它先返回空白,然后再进行实际操作。

于 2016-06-19T20:52:05.217 回答