Parse URL image

Asked

Viewed 53 times

0

How can I do instead of sending an parse to the location it parses an image from a remote address or a url. Because if I try to replace the address: C: Users Format Downloads JRMJ.jpg with a URL the error message is displayed: 'There is no support for the given path format.'

Code:

  protected void Button1_Click(object sender, EventArgs e)
{
    string imageFilePath = @"C:\Users\madureira\Downloads\JRMJ.jpg";
    Literal1.Text= ObterEmocoes(imageFilePath);
}


  public async Task<string> ObterEmocoes(string imageFilePath)
    {
        HttpResponseMessage respostaHttp;
        string json;

        byte[] byteData = GetImageAsByteArray(imageFilePath);

        string url = "https://brazilsouth.api.cognitive.microsoft.com/face/v1.0/detect";

        string queryString = "returnFaceId=true&returnFaceLandmarks=false" +
            "&returnFaceAttributes=age,gender,headPose,smile,facialHair,glasses," +
            "emotion,hair,makeup,occlusion,accessories,blur,exposure,noise";

        var httpClient = new HttpClient();
        httpClient.DefaultRequestHeaders.Add("Ocp-Apim-Subscription-Key", "<<key>>");
        using (ByteArrayContent content = new ByteArrayContent(byteData))
        {
            content.Headers.ContentType = new MediaTypeHeaderValue("application/octet-stream");
            respostaHttp = await httpClient.PostAsync($"{url}?{queryString}", content);
            json = await respostaHttp.Content.ReadAsStringAsync();
        }
        return json;
    }

    static byte[] GetImageAsByteArray(string imageFilePath)
    {
        using (FileStream fileStream =
            new FileStream(imageFilePath, FileMode.Open, FileAccess.Read))
        {
            BinaryReader binaryReader = new BinaryReader(fileStream);
            return binaryReader.ReadBytes((int)fileStream.Length);
        }
    }
  • I understand you’re using the services of Cognitive Services of Microsoft, which does not seem to support remote images. Why not do the download image temporarily, treat and then remove it?

  • @madujr, managed to evolve?

1 answer

1


If what you send is a byte[] and want to get it also from an external url, add this functionality to the method GetImageAsByteArray() or create a new specific.

static byte[] GetImageAsByteArrayFromUrl(string imageUrlPath)
{
    byte[] byteData = null;

    using (var client = new System.Net.WebClient())
    {
        var url = new Uri(imageUrlPath);
        byteData = client.DownloadData(url);
    }

    return byteData;
}
  • Thank you very much it worked!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.