Reputation: 65
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?
Upvotes: 2
Views: 1981
Reputation: 11
var jsonPath = "<YOUR PATH>";
var imageAnnotatorClientBuilder = new ImageAnnotatorClientBuilder
{
CredentialsPath = jsonPath
};
var client = imageAnnotatorClientBuilder.Build();
IReadOnlyList<EntityAnnotation> textAnnotations = client.DetectText(image);
foreach (EntityAnnotation text in textAnnotations)
{
Console.WriteLine($"Description: {text.Description}");
}
Upvotes: 1
Reputation: 48
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);
}
}
}
}
Upvotes: 3