我正在从此链接实现谷歌云视觉API。
下面是我遇到异常的代码:
private void callCloudVision(final Bitmap bitmap) throws IOException {
new AsyncTask<Object, Void, String>() {
@Override
protected String doInBackground(Object... params) {
try {
List<AnnotateImageRequest> requests = new ArrayList<>();
ByteArrayOutputStream bos = new ByteArrayOutputStream();
bitmap.compress(Bitmap.CompressFormat.PNG, 0 /*ignored for PNG*/, bos);
byte[] bitmapdata = bos.toByteArray();
ByteArrayInputStream bs = new ByteArrayInputStream(bitmapdata);
ByteString imgBytes = ByteString.readFrom(bs);
Image img = Image.newBuilder().setContent(imgBytes).build();
Feature feat = Feature.newBuilder().setType(Feature.Type.WEB_DETECTION).build();
AnnotateImageRequest request = AnnotateImageRequest.newBuilder().addFeatures(feat).setImage(img).build();
requests.add(request);
***//Getting exception here at the time of execution...***
try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) {
BatchAnnotateImagesResponse response = client.batchAnnotateImages(requests);
List<AnnotateImageResponse> responses = response.getResponsesList();
for (AnnotateImageResponse res : responses) {
if (res.hasError()) {
System.out.printf("Error: %s\n", res.getError().getMessage());
return "";
}
System.out.println("\nPages with matching images: Score\n==");
for (WebDetection.WebPage page : annotation.getPagesWithMatchingImagesList()) {
System.out.println(page.getUrl() + " : " + page.getScore());
}
}
}
return "";
} catch (Exception e) {
Log.d("LOG_TAG", "Request failed: " + e.getMessage());
return "Cloud Vision API request failed.";
}
}
protected void onPostExecute(String result) {
}
}.execute();
}
我收到错误
java.io.IOException:应用程序默认凭据不可用。如果在 Google Compute Engine 中运行,则它们可用。否则,必须定义环境变量 GOOGLE_APPLICATION_CREDENTIALS 指向定义凭据的文件。请参阅 https://developers.google.com/accounts/docs/application-default-credentials 了解更多信息。
我的毕业生
implementation 'com.android.support.constraint:constraint-layout:1.0.2'
compile fileTree(dir: 'libs', include: ['*.jar'])
compile 'com.android.support:appcompat-v7:26.+'
**compile 'com.google.cloud:google-cloud-vision:1.21.0'**
compile group: 'com.google.apis', name: 'google-api-services-sqladmin', version: 'v1beta4-rev52-1.23.0'
compile('com.google.api-client:google-api-client-android:1.22.0') {
exclude module: 'httpclient'
exclude group: 'com.google.guava'
}
compile('com.google.http-client:google-http-client-gson:1.20.0') {
exclude module: 'httpclient'
exclude group: 'com.google.guava'
}
如错误消息所述,应用程序默认凭据在 Android 上不可用。我建议使用 API 密钥来轻松验证您对 Cloud Vision API 的请求。您可以在此 Github 页面上找到示例代码。