如何在Eclipse的Java项目中导入Google Vision API?
Hey there! I’ve tackled this exact setup a bunch of times, so let’s break it down into straightforward, actionable steps to get you up and running with Google Vision API in your Eclipse Java project.
1. Prepare Google Cloud Project & Service Account Credentials
First, you need to lay the groundwork on Google Cloud:
- Head to the Google Cloud Console, create a new project (or use an existing one if you have one).
- Search for "Cloud Vision API" in the API Library, then click Enable to turn it on for your project.
- Navigate to IAM & Admin > Service Accounts, click Create Service Account. Give it a simple name like "vision-api-service", then click Create and Continue.
- Assign the Cloud Vision API Admin role (or a more restricted role if you want tighter permissions), then click Continue and Done.
- Find your new service account in the list, go to the Keys tab > Add Key > Create New Key. Choose JSON as the key type, then click Create. Save this JSON file somewhere safe—I recommend putting it in your Eclipse project’s root directory for easy access later.
2. Set Up Dependencies in Eclipse
You have two solid options here—Maven (the easier choice for dependency management) or manual JAR import:
Option A: Using Maven (Recommended)
If your project is a Maven project:
- Open your
pom.xmlfile, add this dependency inside the<dependencies>section:<dependency> <groupId>com.google.cloud</groupId> <artifactId>google-cloud-vision</artifactId> <version>2.32.0</version> <!-- Check for the latest version on Maven Central if needed --> </dependency> - Right-click your project in Eclipse > Maven > Update Project. Check "Force Update of Snapshots/Releases" and click OK. Eclipse will automatically download all required dependencies for you.
Option B: Manual JAR Import (For Non-Maven Projects)
If you’re not using Maven:
- Go to Maven Central, search for
google-cloud-vision, download the latest JAR file. - You’ll also need all its transitive dependencies (like
google-cloud-core,grpc-netty-shaded, etc.). The easiest way to get these is to download the "bundle" JAR or use a tool like Maven Dependency Plugin to list all required JARs. - In Eclipse, right-click your project > Build Path > Add External Archives. Select all the downloaded JAR files and click Open.
3. Configure Credentials in Your Project
Your Java app needs to know where to find the service account key—here are two ways to set this up:
- Option 1: Environment Variable (Best for Production)
- On Windows: Set the system environment variable
GOOGLE_APPLICATION_CREDENTIALSto the full path of your JSON key file (e.g.,C:\projects\my-eclipse-project\my-key.json). - On macOS/Linux: Run
export GOOGLE_APPLICATION_CREDENTIALS="/path/to/your/my-key.json"in your terminal before launching Eclipse, or add this line to your shell config file (like.bashrcor.zshrc).
- On Windows: Set the system environment variable
- Option 2: Hardcode Path in Code (For Testing Only)
If you don’t want to set an environment variable (not recommended for production), you can load the key directly in your code:import com.google.auth.oauth2.GoogleCredentials; import com.google.cloud.vision.v1.ImageAnnotatorClient; import java.io.FileInputStream; public class VisionTest { public static void main(String[] args) throws Exception { GoogleCredentials credentials = GoogleCredentials.fromStream(new FileInputStream("path/to/your/my-key.json")); try (ImageAnnotatorClient client = ImageAnnotatorClient.create(ImageAnnotatorSettings.newBuilder().setCredentialsProvider(() -> credentials).build())) { // Your Vision API code will go here } } }
4. Test with a Sample Code
Let’s write a quick test to confirm everything works. This example detects labels in an image:
import com.google.cloud.vision.v1.AnnotateImageRequest; import com.google.cloud.vision.v1.AnnotateImageResponse; import com.google.cloud.vision.v1.Feature; import com.google.cloud.vision.v1.Image; import com.google.cloud.vision.v1.ImageAnnotatorClient; import com.google.protobuf.ByteString; import java.nio.file.Files; import java.nio.file.Paths; import java.util.ArrayList; import java.util.List; public class VisionLabelDetection { public static void main(String[] args) throws Exception { // Path to your test image (replace with your own image path) String imagePath = "path/to/your/test-image.jpg"; // Read image into ByteString ByteString imgBytes = ByteString.readFrom(Files.newInputStream(Paths.get(imagePath))); // Build the image request Image image = Image.newBuilder().setContent(imgBytes).build(); Feature feature = Feature.newBuilder().setType(Feature.Type.LABEL_DETECTION).build(); AnnotateImageRequest request = AnnotateImageRequest.newBuilder() .addFeatures(feature) .setImage(image) .build(); List<AnnotateImageRequest> requests = new ArrayList<>(); requests.add(request); // Initialize client and run detection try (ImageAnnotatorClient client = ImageAnnotatorClient.create()) { List<AnnotateImageResponse> responses = client.batchAnnotateImages(requests).getResponsesList(); for (AnnotateImageResponse res : responses) { if (res.hasError()) { System.out.printf("Error: %s%n", res.getError().getMessage()); return; } // Print detected labels System.out.println("Detected labels:"); for (com.google.cloud.vision.v1.LabelAnnotation annotation : res.getLabelAnnotationsList()) { System.out.printf("- %s (score: %.2f)%n", annotation.getDescription(), annotation.getScore()); } } } } }
Run this class in Eclipse—if you see the detected labels printed out, you’ve successfully set up the Vision API!
Common Pitfalls to Avoid
- Forgot to Enable Vision API: If you get a "PERMISSION_DENIED" error, double-check that the API is enabled for your Google Cloud project.
- Incorrect Credential Path: Make sure the path to your JSON key is accurate, especially if you’re using the environment variable.
- Missing Dependencies: If you get
NoClassDefFoundError, ensure all required JARs are included (Maven handles this automatically, so it’s the better choice).
内容的提问来源于stack exchange,提问作者Darko

