Save Barcode Images to and Retrieve from MySQL Database
This article uses Aspose.BarCode for Java to generate a barcode image and save it to a MySQL database. It also shows how to retrieve the barcode image from the database and then recognize code text from it.
Aspose.BarCode for Java has built-in support for saving barcode images to disk. But it is also possible to store and retrieve barcode images to and from a MySQL database using Java.
MySQL Database Preparation
To use the code snippets in this tutorial, you need access to a MySQL database. To enable Java to connect to MySQL, install MySQL JDBC drivers.
Create a new schema and table in MySQL using the following SQL statement:
SQL
DROP TABLE IF EXISTS test.product;
CREATE TABLE test.product (
ID int(10) unsigned NOT NULL AUTO_INCREMENT,
ProductNumber varchar(45) NOT NULL,
ProductName varchar(45) NOT NULL,
BarCodeImage blob,
PRIMARY KEY (ID)
) ENGINE=InnoDB AUTO_INCREMENT=10 DEFAULT CHARSET=latin1;
The above SQL statement creates a new table called product in the test schema. The table has the following columns:
- ID (Integer)
- ProductNumber (Varchar) stores the product number.
- ProductName (Varchar)
- BarCodeImage (Blob) stores the barcode image in binary form.
Generate Barcode and Store in Database
Create a Java program that will generate a barcode image and then store the image in the product table’s BarCodeImage column. The data type of this column is blob so that it can contain binary data.
Below is the full listing of the program.
public class Common | |
{ | |
public static String HOST_URI = "jdbc:mysql://host/test"; | |
public static String USERNAME = "root"; | |
public static String PASSWORD = "pwd"; | |
} |
import java.io.File; | |
import java.io.FileInputStream; | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.PreparedStatement; | |
import com.aspose.barcode.EncodeTypes; | |
import com.aspose.barcode.generation.BarcodeGenerator; | |
// This class will generate a barcode image, save it to file on disk | |
// then create the stream from file and insert the image stream into DB (BLOB type column) | |
public class GenerateAndSaveBarCode { | |
public void PerformInsertExample() { | |
try { | |
// Step-1 - Generate barcode and save temporarily in a file | |
String strBarCodeImage = "c:\\temp\\code39.jpg"; | |
String strCodeText = "NOK-E71"; | |
BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.CODE_39_STANDARD); | |
generator.setCodeText(strCodeText); | |
generator.save(strBarCodeImage); | |
// Step-2 - insert a new record in MySQL DB | |
Connection con = null; | |
// Open connection | |
Class.forName("com.mysql.jdbc.Driver").newInstance(); | |
con = DriverManager.getConnection(Common.HOST_URI, Common.USERNAME, Common.PASSWORD); | |
// Prepare statement | |
PreparedStatement pre = con.prepareCall( | |
"Insert INTO Product (ProductNumber, ProductName, BarCodeImage) " + "VALUES (?, ?, ?) "); | |
// Set product number and product name | |
pre.setString(1, "NOK-E71"); | |
pre.setString(2, "Nokia E Series - E71"); | |
// 3rd column is for barcode image. DB type is BLOB | |
// for saving the image, we need to create stream from the image file | |
File imgFile = new File(strBarCodeImage); | |
FileInputStream fin = new FileInputStream(imgFile); | |
pre.setBinaryStream(3, fin, (int) imgFile.length()); | |
// Now execute the statement | |
pre.executeUpdate(); | |
System.out.println("Insertion successfull."); | |
// Close connection | |
pre.close(); | |
con.close(); | |
} catch (Exception ex) { | |
System.out.println(ex.getMessage()); | |
} | |
} | |
public void PerformUpdateExample() { | |
try { | |
// Step-1 - Generate barcode and save temporarily in a file | |
String strBarCodeImage = "c:\\temp\\code39.jpg"; | |
String strCodeText = "NOK-E71-UPDATED"; | |
BarcodeGenerator generator = new BarcodeGenerator(EncodeTypes.CODE_39_STANDARD); | |
generator.setCodeText(strCodeText); | |
generator.save(strBarCodeImage); | |
// Step-2 - update the record in MySQL DB | |
Connection con = null; | |
// Open connection | |
Class.forName("com.mysql.jdbc.Driver").newInstance(); | |
con = DriverManager.getConnection(Common.HOST_URI, Common.USERNAME, Common.PASSWORD); | |
// Prepare statement | |
PreparedStatement pre = con.prepareCall("UPDATE Product SET BarCodeImage = ? WHERE ProductNumber = ? "); | |
// Barcode image column. DB type is BLOB | |
// For saving the image, we need to create stream from the image file | |
File imgFile = new File(strBarCodeImage); | |
FileInputStream fin = new FileInputStream(imgFile); | |
pre.setBinaryStream(1, fin, (int) imgFile.length()); | |
// 2nd column in where condition is the ProductNumber | |
pre.setString(2, "NOK-E71"); | |
// Now execute the statement | |
pre.executeUpdate(); | |
System.out.println("Update successfull."); | |
// Close connection | |
pre.close(); | |
con.close(); | |
} catch (Exception ex) { | |
System.out.println(ex.getMessage()); | |
} | |
} | |
} |
In the above code snippet, a class called {{GenerateAndSaveBarCode} is created. It contains two methods:
- PerformInsertExample – Insert barcode image in MySQL database. This method first uses Aspose.BarCode for Java to generate a Code39Standard barcode image and save it on the disk. Then it creates a connection with the MySQL database using MySQL JDBC drivers. After that, we created an object of type PreparedStatement and supplies the “INSERT” SQL query for creating a new record in the table. Then we create a stream from the file (saved image) and set the value of the BarCodeImage column to this stream. Since the data type is a blob, it can store a stream. Finally, the statement is executed and the database connection is closed.
- PerformUpdateExample – Update barcode image to MySQL database. This method also generates a barcode image and saves it to disk. Then it uses the UPDATE SQL statement to update the record in the table.
Retrieve Barcode Image from Database and Recognize Barcode
Now, fetch all the records from the product table and construct an image from the BarCodeImage column. Then, pass the image to Aspose.BarCode for Java to recognize CodeText. Below is the code snippet for barcode recognition.
import java.io.FileOutputStream; | |
import java.io.InputStream; | |
import java.io.OutputStream; | |
import java.sql.Connection; | |
import java.sql.DriverManager; | |
import java.sql.PreparedStatement; | |
import java.sql.ResultSet; | |
import com.aspose.barcode.barcoderecognition.BarCodeReader; | |
import com.aspose.barcode.barcoderecognition.BarCodeResult; | |
import com.aspose.barcode.barcoderecognition.DecodeType; | |
// This class will select the records from MySQL DB | |
// read a BLOB type column to fetch image stream from DB | |
// construct a file on disk and recognize the barcode from the image | |
public class FetchAndRecognizeBarCode { | |
public void PerformRecognition() { | |
try { | |
String strBarCodeImage = "c:\\temp\\code39.jpg"; | |
// Step-1 - Select the record from the DB on the basis of ProductNumber | |
// String strProductNumber = "NOK-E71"; | |
// Open a connection to the database | |
Connection con = null; | |
Class.forName("com.mysql.jdbc.Driver").newInstance(); | |
con = DriverManager.getConnection(Common.HOST_URI, Common.USERNAME, Common.PASSWORD); | |
// Create a statement to execute the SELECT SQL | |
PreparedStatement st = con.prepareStatement("SELECT * FROM Product "); | |
// st.setString(1, strProductNumber); | |
st.executeQuery(); | |
// Get the resultset | |
ResultSet rs = st.getResultSet(); | |
// Now check if we have any record in the resultset | |
int nCount = 0; | |
while (rs.next()) { | |
// We got a record, read BLOB field and create image from it | |
String len1 = rs.getString("BarCodeImage"); | |
int len = len1.length(); | |
byte[] b = new byte[len]; | |
// Create stream to read the image | |
InputStream in = rs.getBinaryStream("BarCodeImage"); | |
// Write the stream to a file | |
int index = in.read(b, 0, len); | |
OutputStream outImgBarCode = new FileOutputStream(strBarCodeImage); | |
while (index != -1) { | |
// Write bytes to file | |
outImgBarCode.write(b, 0, index); | |
// Read next bytes | |
index = in.read(b, 0, len); | |
} | |
// Close the stream and connection | |
outImgBarCode.close(); | |
// Now that we have got the image from the database | |
// read the barcode from the image | |
BarCodeReader reader = new BarCodeReader(strBarCodeImage, DecodeType.CODE_39_STANDARD); | |
for (BarCodeResult result : reader.readBarCodes()) { | |
System.out.println("CodeText: " + result.getCodeText()); | |
System.out.println("Symbology type: " + result.getCodeType()); | |
} | |
nCount++; | |
} | |
System.out.println(nCount + " records found."); | |
con.close(); | |
} catch (Exception ex) { | |
System.out.println(ex.getMessage()); | |
} | |
} | |
} |
The above code snippet creates a connection to the MySQL database and executes the SELECT SQL statement on the product table. It then loops through the Resultset and calls the ResultSet.getBinaryStream() method on the BarCodeImage column. Because it is a blob type column, the method returns an object of the type InputStream. Use this stream to write the data to a new file (the image file) and save the file to disk. When the data is saved, pass the path and file name to the BarCodeReader class to recognize the CodeText
All the above code snippets are separate class files. We need another class with a main()}] method to use them. Below is the code snippet of the {{Main class.
public class Main { | |
public static void main(String[] args) { | |
// To insert and update barcode image in MySQL DB | |
GenerateAndSaveBarCode sample1 = new GenerateAndSaveBarCode(); | |
sample1.PerformInsertExample(); | |
sample1.PerformUpdateExample(); | |
// To fetch the image from DB and recognize codetext | |
FetchAndRecognizeBarCode sample2 = new FetchAndRecognizeBarCode(); | |
sample2.PerformRecognition(); | |
} | |
} |