Java條形碼SDK示例:命令行,界面,網絡

這篇文章分享下ZXingDynamsoft Java Barcode SDK在三種場景下的使用。

Java Barcode應用

我的測試圖片包含了各種類型的條形碼。
在這裏插入圖片描述
在Maven的配置文件中添加ZXing和Dynamsoft Barcode Reader:

<repositories>
        <repository>
            <id>dbr</id>
            <url>https://download.dynamsoft.com/maven/dbr/jar</url>
        </repository>
</repositories>
<dependencies>
        <dependency>
            <groupId>com.dynamsoft</groupId>
            <artifactId>dbr</artifactId>
            <version>7.3</version>
        </dependency>
        <dependency>
            <groupId>com.google.zxing</groupId>
            <artifactId>core</artifactId>
            <version>3.4.0</version>
          </dependency>
</dependencies>

命令行

新建一個Maven工程:

mvn archetype:generate -DgroupId=com.java.barcode -DartifactId=app -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false

導入需要用的條形碼庫:

import com.dynamsoft.barcode.*;
import com.google.zxing.BinaryBitmap;
import com.google.zxing.MultiFormatReader;
import com.google.zxing.NotFoundException;
import com.google.zxing.RGBLuminanceSource;
import com.google.zxing.Result;
import com.google.zxing.common.HybridBinarizer;
import com.google.zxing.multi.*;

使用ImageIOBufferedImage讀入圖片:

import java.awt.image.*;
import javax.imageio.ImageIO;
BufferedImage image = null;
try {
    image = ImageIO.read(new File(filename));
} catch (IOException e) {
    System.out.println(e);
    return;
}

ZXing讀取多個條形碼和單個條形碼用到的類是不同的。以下是讀取多個條形碼的方法:

BinaryBitmap bitmap = null;
int[] pixels = image.getRGB(0, 0, image.getWidth(), image.getHeight(), null, 0, image.getWidth());
RGBLuminanceSource source = new RGBLuminanceSource(image.getWidth(), image.getHeight(), pixels);
bitmap = new BinaryBitmap(new HybridBinarizer(source));
             
MultiFormatReader reader = new MultiFormatReader();  
GenericMultipleBarcodeReader multiReader = new GenericMultipleBarcodeReader(reader);
try {
    Result[] zxingResults = multiReader.decodeMultiple(bitmap);
} catch (NotFoundException e) {
    e.printStackTrace();
}
pixels = null;
bitmap = null;

使用Dynamsoft Barcode Reader比較簡單,接口默認就可以識別多個條形碼:

BarcodeReader br = null;
try {
    br = new BarcodeReader("LICENSE-KEY");
} catch (Exception e) {
    System.out.println(e);
    return;
}
 
TextResult[] results = null;
try {
    results = br.decodeBufferedImage(image, "");
} catch (Exception e) {
    System.out.println("decode buffered image: " + e);
}

爲了方便運行,用Maven插件打包所有依賴:

<build>
  <plugins>
    <plugin>
        <artifactId>maven-assembly-plugin</artifactId>
        <configuration>
            <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
            </descriptorRefs>
        </configuration>
    </plugin>
  </plugins>
</build>

編譯運行工程:

mvn clean install assembly:assembly -Dmaven.test.skip=true
java -cp target/command-line-1.0-SNAPSHOT-jar-with-dependencies.jar com.java.barcode.App ..\images\AllSupportedBarcodeTypes.png

運行結果:

在這裏插入圖片描述

界面

基於命令行的代碼,用Swing實現界面。
導入相關的類:

import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.JButton;
import javax.swing.JFileChooser;
import javax.swing.JFrame;
import javax.swing.JComboBox;
import javax.swing.SwingUtilities;
import javax.swing.UIManager;
import javax.swing.filechooser.FileNameExtensionFilter;
 
import java.awt.BorderLayout;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

添加組件JTextArea, JButton, JFileChooser,JComboBox:

public App() {
    super(new BorderLayout());
     
    mFileChooser = new JFileChooser();
    FileNameExtensionFilter filter = new FileNameExtensionFilter(
            ".png", "png");
    mFileChooser.setFileFilter(filter);
    mLoad = new JButton("Load File");
    mLoad.addActionListener(this);
     
    mSourceList = new JComboBox(new String[]{"ZXing", "Dynamsoft"});
    mSourceList.setSelectedIndex(0);
     
    JPanel buttonPanel = new JPanel(); 
    buttonPanel.add(mSourceList);
    buttonPanel.add(mLoad);
    add(buttonPanel, BorderLayout.PAGE_START);
     
    mTextArea = new JTextArea();
    mTextArea.setSize(480, 480);
    JScrollPane sp = new JScrollPane(mTextArea); 
    add(sp, BorderLayout.CENTER);
}

添加按鈕響應:

public void actionPerformed(ActionEvent e) {
 
    int returnVal = mFileChooser.showOpenDialog(App.this);
 
    if (returnVal == JFileChooser.APPROVE_OPTION) {
        File file = mFileChooser.getSelectedFile();     
        String filename = file.toPath().toString();          
        if (mSourceList.getSelectedItem().toString().equals("Dynamsoft")) {
            TextResult[] results = decodefileDynamsoft(filename);
        }
        else {
            Result[] results = decodefileZXing(filename);
        }
    } 
}

編譯運行:

mvn clean install assembly:assembly -Dmaven.test.skip=true
java -cp target/gui-1.0-SNAPSHOT-jar-with-dependencies.jar com.java.barcode.App

在這裏插入圖片描述

網絡

根據Spring Boot的入門指南來創建一個簡單的web應用。
在pom.xml中添加:

<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-core</artifactId>
    <version>1.1.45</version>
    <exclusions>
        <exclusion>
            <groupId>io.github.classgraph</groupId>
            <artifactId>classgraph</artifactId>
        </exclusion>
    </exclusions>
</dependency>
<dependency>
    <groupId>org.springdoc</groupId>
    <artifactId>springdoc-openapi-ui</artifactId>
    <version>1.1.45</version>
</dependency>

這樣就可以通過swagger-ui來測試server端的接口。
創建server端的代碼:

@RestController
public class BarcodeController {
 
    private DynamsoftBarcode mDynamsoftBarcode;
    private ZXingBarcode mZXingBarcode;
 
    @Autowired
    public BarcodeController(DynamsoftBarcode dynamsoft, ZXingBarcode zxing) 
    {
        mDynamsoftBarcode = dynamsoft;
        mZXingBarcode = zxing;
    }
 
    @PostMapping(value = "/api/dynamsoft"
            , consumes = MediaType.MULTIPART_FORM_DATA_VALUE
            , produces = MediaType.APPLICATION_JSON_VALUE)
    public BarcodeResponse getDynamsoft(@RequestPart MultipartFile file) throws Exception {
        return mDynamsoftBarcode.decode(file.getOriginalFilename(), file.getInputStream());
    }
 
    @PostMapping(value = "/api/zxing"
            , consumes = MediaType.MULTIPART_FORM_DATA_VALUE
            , produces = MediaType.APPLICATION_JSON_VALUE)
    public BarcodeResponse getZXing(@RequestPart MultipartFile file) throws Exception {
        return mZXingBarcode.decode(file.getOriginalFilename(), file.getInputStream());
    }
}

編譯運行:

mvn clean install
java -jar target/web-1.0-SNAPSHOT.jar

打開http://localhost:8080/swagger-ui.html 測試接口。
在這裏插入圖片描述

安卓開發

如果要給安卓開發,在gradle中添加:

allprojects {
    repositories {
        google()
        jcenter()
        maven {
            url "http://download.dynamsoft.com/maven/dbr/aar"
        }
    }
}
implementation 'com.google.zxing:core:3.4.0'
implementation 'com.dynamsoft:dynamsoftbarcodereader:7.3.0'

源碼

https://github.com/yushulx/java-barcode-command-gui-web

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章