| layout | default-layout |
|---|---|
| title | User Guide - Dynamsoft Barcode Reader SDK Java Edition |
| description | A step-by-step guide to building your first barcode reading application with DBR Java Edition, covering installation, single-image decoding, and multi-image processing with code samples. |
| keywords | user guide, java |
| needAutoGenerateSidebar | true |
| needGenerateH3Content | true |
| noTitleIndex | true |
In this guide, you will learn step by step on how to build a barcode reading application with Dynamsoft Barcode Reader SDK using Java.
Read more on Dynamsoft Barcode Reader Features
- Getting Started with Dynamsoft Barcode Reader SDK Java Edition
- System Requirements
- Installation
- Build Your First Application
- Process Multiple Images
- Create an ImageSource as the Input
- Implement a CapturedResultReceiver as the Output Listener
- Handle Capture Stoppage by Implementing an ImageSource State Listener
- Register the Input, Output Listener and ImageSource State Listener to the CaptureVisionRouter Instance
- Start the Capturing Process
- Build and Run the Project Again
To find out whether your environment is supported, please read the [System Requirements]({{ site.dbr_java }}index.html#system-requirements).
If you don't have a Maven project, you can create one with the following steps:
- Create a new directory for your project
- Navigate to the directory and run the following command to create a Maven project:
mvn archetype:generate -DgroupId=com.dynamsoft -DartifactId=dbr-hello-world -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
- Add the Dynamsoft Barcode Reader dependency to your
pom.xmlfile:
<repositories>
<repository>
<id>dbr</id>
<url>https://download2.dynamsoft.com/maven/dbr/jar</url>
</repository>
</repositories>
<dependencies>
<dependency>
<groupId>com.dynamsoft</groupId>
<artifactId>dbr</artifactId>
<version>11.4.1000</version>
</dependency>
</dependencies>Let's start by creating a console application which demonstrates how to use the minimum code to read barcodes from an image file.
Create a new Java source file named ReadAnImage.java in your project's src/main/java directory.
Import the necessary packages at the beginning of your Java file:
import com.dynamsoft.core.EnumErrorCode;
import com.dynamsoft.cvr.CaptureVisionRouter;
import com.dynamsoft.cvr.CapturedResult;
import com.dynamsoft.cvr.EnumPresetTemplate;
import com.dynamsoft.dbr.BarcodeResultItem;
import com.dynamsoft.dbr.DecodedBarcodesResult;
import com.dynamsoft.license.LicenseError;
import com.dynamsoft.license.LicenseException;
import com.dynamsoft.license.LicenseManager;Add the following code inside the main method to initialize the license for using the SDK in the application:
public class ReadAnImage {
public static void main(String[] args) {
try {
LicenseError licenseError = LicenseManager.initLicense("DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9");
if (licenseError.getErrorCode() != EnumErrorCode.EC_OK) {
System.out.println("License initialization failed: ErrorCode: " + licenseError.getErrorCode() + ", ErrorString: " + licenseError.getErrorString());
return;
}
} catch (LicenseException e) {
System.out.println("License initialization failed: ErrorCode: " + e.getErrorCode() + ", ErrorString: " + e.getErrorString());
return;
}
// codes from following steps
}
}The string "DLS2eyJvcmdhbml6YXRpb25JRCI6IjIwMDAwMSJ9" here is a free public trial license. Note that network connection is required for this license to work. Alternatively, you can request a 30-day free offline trial license from the Customer Portal.
CaptureVisionRouter cvRouter = new CaptureVisionRouter();CapturedResult[] results = cvRouter.captureMultiPages("[PATH-TO-THE-IMAGE-FILE]", EnumPresetTemplate.PT_READ_BARCODES);Please change the
[PATH-TO-THE-IMAGE-FILE]to a real barcode image file path.
if (results == null || results.length == 0) {
System.out.println("No barcode detected.");
} else {
for (int index = 0; index < results.length; index++) {
CapturedResult result = results[index];
if (result.getErrorCode() != EnumErrorCode.EC_OK) {
System.out.println("Error: " + result.getErrorCode() + ", " + result.getErrorString());
}
DecodedBarcodesResult barcodeResult = result.getDecodedBarcodesResult();
BarcodeResultItem[] items = barcodeResult != null ? barcodeResult.getItems() : null;
if (items == null || items.length == 0) {
System.out.println("No barcode detected.");
} else {
System.out.println("Decoded " + items.length + " barcodes.");
for (int i = 0; i < items.length; i++) {
BarcodeResultItem item = items[i];
System.out.println("Result " + (i + 1));
System.out.println("Barcode Format: " + item.getFormatString());
System.out.println("Barcode Text: " + item.getText());
}
}
}
}- Save the
ReadAnImage.javafile. - Open terminal or command prompt and navigate to the project root directory.
- Compile and run the project using Maven:
mvn compile exec:java "-Dexec.mainClass=ReadAnImage"
- You will see the output message in the console like
Decoded 2 barcodes
Result 1
Barcode Format: XXX
Barcode Text: XXX
Result 2
Barcode Format: XXX
Barcode Text: XXX
If, instead of processing one single image, you need to process many images at once, you can follow these steps:
These steps follow the step Create a CaptureVisionRouter Instance mentioned above.
An ImageSource is required when creating a multi-image processing application. You can either utilize ready-made image sources such as [FileFetcher]({{ site.dcvb_java_api }}utility/file-fetcher.html) and [DirectoryFetcher]({{ site.dcvb_java_api }}utility/directory-fetcher.html), or customize your own image source based on the base class [ImageSourceAdapter]({{ site.dcvb_java_api }}core/basic-classes/image-source-adapter.html).
First, you need to import the additional required classes:
import com.dynamsoft.core.basic_structures.FileImageTag;
import com.dynamsoft.core.basic_structures.ImageTag;
import com.dynamsoft.cvr.*;
import com.dynamsoft.utility.DirectoryFetcher;
import com.dynamsoft.utility.UtilityException;In this sample, we will use the DirectoryFetcher to retrieve images from a local directory.
DirectoryFetcher fetcher = new DirectoryFetcher();
fetcher.setDirectory("[THE DIRECTORY THAT HOLDS THE IMAGES]");Please change the
[THE DIRECTORY THAT HOLDS THE IMAGES]to full path of the directory holding barcode image files.
Create a class MyCapturedResultReceiver to extend the CapturedResultReceiver class, and get the barcode results in onDecodedBarcodesReceived callback method.
class MyCapturedResultReceiver extends CapturedResultReceiver {
@Override
public void onDecodedBarcodesReceived(DecodedBarcodesResult result) {
ImageTag tag = result.getOriginalImageTag();
if (tag instanceof FileImageTag) {
System.out.println("File: " + ((FileImageTag)tag).getFilePath());
}
if (result.getErrorCode() != EnumErrorCode.EC_OK) {
System.out.println("Error: " + result.getErrorString());
} else {
BarcodeResultItem[] items = result.getItems();
System.out.println("Decoded " + items.length + " barcodes.");
for (int index = 0; index < items.length; index++) {
BarcodeResultItem item = items[index];
System.out.println("Result " + (index + 1));
System.out.println("Barcode Format: " + item.getFormatString());
System.out.println("Barcode Text: " + item.getText());
}
}
}
}Create a class MyImageSourceStateListener to implement the ImageSourceStateListener interface, and call stopCapturing in onImageSourceStateReceived callback method when the state is ISS_EXHAUSTED.
class MyImageSourceStateListener implements ImageSourceStateListener {
CaptureVisionRouter cvRouter;
public MyImageSourceStateListener(CaptureVisionRouter cvRouter) {
this.cvRouter = cvRouter;
}
@Override
public void onImageSourceStateReceived(int state) {
if (state == EnumImageSourceState.ISS_EXHAUSTED) {
if (cvRouter != null) {
cvRouter.stopCapturing();
}
}
}
}Register the Input, Output Listener and ImageSource State Listener to the CaptureVisionRouter Instance
try {
cvRouter.setInput(fetcher);
MyCapturedResultReceiver receiver = new MyCapturedResultReceiver();
cvRouter.addResultReceiver(receiver);
MyImageSourceStateListener listener = new MyImageSourceStateListener(cvRouter);
cvRouter.addImageSourceStateListener(listener);
} catch (CaptureVisionException e) {
System.out.println("Error setting up capture vision router: " + e.getMessage());
}Call the method startCapturing() to start processing all the images in the specified folder.
try {
cvRouter.startCapturing("", true);
} catch (CaptureVisionException e) {
if (e.getErrorCode() != EnumErrorCode.EC_OK) {
System.out.println("Error: " + e.getErrorCode());
}
}During the process, the callback method onDecodedBarcodesReceived() is triggered each time processing of an image is finished. After all images are processed, the listener method onImageSourceStateReceived() will be triggered while the image source state is ISS_EXHAUSTED and the process is stopped with the method stopCapturing().
Please refer to Build and Run the Project.