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
相关产品推荐
相关产品推荐

