How to Perform OCR in Java with Spire.OCR: Step‑by‑Step Guide
This tutorial shows how to set up the Spire.OCR library in Java, configure dependencies, and write code that scans images to extract their text, complete with Maven setup, project configuration, and sample output.
Image text cannot be edited directly; to read text from images you need OCR tools. This article explains how to implement OCR in Java using Spire.OCR.
Required Tools
IDEA
Spire.OCR for Java – Java OCR component supporting multiple languages and image formats.
Download the product package from https://www.e-iceblue.cn/Downloads/Spire-OCR-JAVA.html or import from Maven repository:
<code><repositories>
<repository>
<id>com.e-iceblue</id>
<name>e-iceblue</name>
<url>https://repo.e-iceblue.cn/repository/maven-public/</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>e-iceblue</groupId>
<artifactId>spire.ocr</artifactId>
<version>1.9.0</version>
</dependency>
</dependencies></code>Other dependency files should be downloaded for the corresponding OS and extracted to the specified path (Linux, Windows x64).
Implementation Steps
1. Create a new project in IDEA and add Spire.OCR.jar.
2. Copy the extracted “dependencies” folder into the project directory.
3. After adding the dependencies, run the following code to scan and read text from an image.
<code>import com.spire.ocr.OcrScanner;
import java.io.*;
public class ReadImage {
public static void main(String[] args) throws Exception {
// Path to dependencies
String dependencies = "dependencies\\";
// Path to the image to scan
String imageFile = "图片.png";
// Output file path
String outputFile = "读取图片.txt";
// Create OcrScanner and set dependencies
OcrScanner scanner = new OcrScanner();
scanner.setDependencies(dependencies);
// Scan the image
scanner.scan(imageFile);
// Get scanned text
String scannedText = scanner.getText().toString();
// Create output file object
File output = new File(outputFile);
// Delete if already exists
if (output.exists()) {
output.delete();
}
// Write scanned text to file
BufferedWriter writer = new BufferedWriter(new FileWriter(outputFile));
writer.write(scannedText);
writer.close();
}
}
</code>Example image:
OCR scan result:
Java Captain
Focused on Java technologies: SSM, the Spring ecosystem, microservices, MySQL, MyCat, clustering, distributed systems, middleware, Linux, networking, multithreading; occasionally covers DevOps tools like Jenkins, Nexus, Docker, ELK; shares practical tech insights and is dedicated to full‑stack Java development.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.