Search code examples
c#google-cloud-visiongoogle-vision

Google Vision API specify JSON file


I'm trying to authenticate to Google Vision API using a JSON file. Normally, I do it using the GOOGLE_APPLICATION_CREDENTIALS environmental variable which specifies the path to the JSON file itself.

However, I am required to specify this in my application itself and authenticate using the JSON file contents.

Now, I have tried to specify CallSettings to then pass it in as a parameter to the ImageAnnotatorClient.Create method. Sure enough, a CallSettings object can be created perfectly by reading the authentication info from the JSON file, but passing it in as a parameter to ImageAnnotatorClient seems to make no difference as the ImageAnnotatorClient.Create method is still looking for the environmental variable and throws an InvalidOperation exception, specifying that the environmental variable cannot be found.

Any idea how I can get the desired behavior?

Google Vision Docs


Solution

  • using System;
    using Google.Apis.Auth.OAuth2;
    using Google.Cloud.Vision.V1;
    using Grpc.Auth;
    
    namespace GoogleVision
    {
        class Program
        {
            static void Main(string[] args)
            {
                string jsonPath = @"<path to .json credential file>";
    
                var credential = GoogleCredential.FromFile(jsonPath).CreateScoped(ImageAnnotatorClient.DefaultScopes);
    
                var channel = new Grpc.Core.Channel(ImageAnnotatorClient.DefaultEndpoint.ToString(), credential.ToChannelCredentials());
    
                var client = ImageAnnotatorClient.Create(channel);
    
                var image = Image.FromFile(@"<path to your image file>");
    
                var response = client.DetectLabels(image);
    
                foreach (var annotation in response)
                {
                    if (annotation.Description != null)
                        Console.WriteLine(annotation.Description);
                }
            }
        }
    }