You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Google Vision API Java SDK1.16.0:如何自定义凭证文件创建ImageAnnotatorClient?

为ImageAnnotatorClient指定自定义凭证(Google Cloud Java SDK 1.16.0)

当然可以!在Google Cloud Java SDK 1.16.0版本中,ImageAnnotatorClient完全支持指定自定义凭证文件,实现逻辑和你已经搞定的Translate API几乎一致,核心是通过构建带凭证的ImageAnnotatorSettings来创建客户端。

下面是具体的代码示例,你可以直接参考复用:

import com.google.cloud.vision.v1.ImageAnnotatorClient;
import com.google.cloud.vision.v1.ImageAnnotatorSettings;
import com.google.auth.oauth2.GoogleCredentials;
import java.io.FileInputStream;
import java.io.IOException;

public class CustomVisionClient {
    public static void main(String[] args) throws IOException {
        // 替换成你的服务账号凭证JSON文件的实际路径
        String serviceAccountPath = "/your/path/to/service-account-key.json";
        
        // 从本地文件加载自定义凭证
        GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream(serviceAccountPath));
        
        // 构建带有自定义凭证的ImageAnnotatorSettings
        ImageAnnotatorSettings settings = ImageAnnotatorSettings.newBuilder()
                .setCredentialsProvider(() -> credentials)
                .build();
        
        // 使用settings创建ImageAnnotatorClient(try-with-resources会自动关闭客户端,避免资源泄漏)
        try (ImageAnnotatorClient visionClient = ImageAnnotatorClient.create(settings)) {
            // 在这里执行你的Vision API操作,比如OCR识别、图像标签检测等
            // 示例:
            // Image image = Image.newBuilder().setContent(ByteString.copyFrom(imageBytes)).build();
            // LabelAnnotationResponse response = visionClient.labelDetection(image);
        }
    }
}

补充说明:

  • Google Cloud的Java客户端基于统一的认证框架,所以你之前在Translate API中用到的凭证加载、Settings配置逻辑,完全可以迁移到Vision API上。
  • 如果需要复用凭证或者配置更多客户端参数(比如超时时间、代理),都可以通过ImageAnnotatorSettings的Builder进行扩展调整。

内容的提问来源于stack exchange,提问作者Zaid Amir

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.19 08:53:35