In this article, we will use Aspose.BarCode for Java to generate barcode image and save it in MySQL database. And then we will also show you how to retrieve the barcode image from database and then recognize codetext from it.
Aspose.BarCode for Java API has built-in support for saving barcode images to disk. But, its also possible to store/retrieve barcode images to/from MySQL database using Java.
MySQL Database Preparation
In order to use code snippets in this tutorial, you must have access to MySQL database. To enable Java to connect to MySQL, you will also need to 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 will create a new table “product” in “test” schema. The table has 4 columns.
- ID of type Integer
- ProductNumber of type Varchar (to store the Product Number)
- ProductName of type Varchar
- BarCodeImage of type Blob (to store the barcode image in binary form)
Generate BarCode and Store in Database
Now, we will create a Java program that will generate a barcode image and then we will store this image in the “product” table’s BarCodeImage column. The data type of this column is set as “Blob”, so that it can contain binary data.
Below is the full listing of the program:
[Java]
// below are the contents of Common.java
package barcodemysql;
public class Common
{
public static String HOST_URI = "jdbc:mysql://host/test";
public static String USERNAME = "root";
public static String PASSWORD = "pwd";
}
// below are the contents of GenerateAndSaveBarCode.java
package barcodemysql;
import com.aspose.barcode.BarCodeBuilder;
import com.aspose.barcode.Symbology;
import java.io.File;
import java.io.FileInputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
// 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";
BarCodeBuilder builder = new BarCodeBuilder();
builder.setSymbology(Symbology.CODE39STANDARD);
builder.setCodeText(strCodeText);
builder.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";
BarCodeBuilder builder = new BarCodeBuilder();
builder.setSymbology(Symbology.CODE39STANDARD);
builder.setCodeText(strCodeText);
builder.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, we create a class named “GenerateAndSaveBarCode”. It contains two methods which are described below:
PerformInsertExample – Insert BarCode Image in MySQL Database
In this method, we first used Aspose.BarCode for Java library to generate a Code39Standard barcode image and saved it in disk. Then we created a connection with MySQL database using MySQL JDBC Drivers. After that we created an object of type “PreparedStatement” and supplied “INSERT” SQL query for creating a new record in the table. Then we create stream from the file (saved image) and set the value of “BarCodeImage” column to this stream. Since, its data type is Blob, it can store stream. Finally, we executed the statement and closed the Database connection.
PerformUpdateExample – Update BarCode Image in MySQL Database
This method also generates a barcode image and saves it to disk. Then it uses “UPDATE” SQL statement to update the record in table.
Retrieve BarCode Image from Database and Recognize BarCode
Now, we will fetch all the records from the “product” table and construct image from “BarCodeImage” column. Then, we will pass this image to Aspose.BarCode for Java to recognize codetext from it. Below is the code snippet for barcode recognition.
[Java]
package barcodemysql;
import com.aspose.barcoderecognition.BarCodeReadType;
import com.aspose.barcoderecognition.BarCodeReader;
import java.awt.Toolkit;
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;
// 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(Toolkit.getDefaultToolkit().getImage(strBarCodeImage), BarCodeReadType.Code39Standard);
while(reader.read())
{
System.out.println("BarCode found: Code Text: " + reader.getCodeText());
}
nCount++;
}
System.out.println(nCount + " records found.");
con.close();
}
catch(Exception ex)
{
System.out.println(ex.getMessage());
}
}
}
In the above code snippet, we created a connection to MySQL database and executed the “SELECT” SQL statement on “product” table. Then we looped through the Resultset and called ResultSet.getBinaryStream() method on “BarCodeImage” column. Since, it’s a Blob type column, the method will return object of type InputStream. We will use this stream to write the data to a new file (which is our image file) and save the file to disk. Once, the data is saved to disk, we will pass the path and file name to BarCodeReader class to recognize the codetext from it.
All the above code snippets are separate class files. We need another class with a main() method to use these classes. Below is the code snippet of the Main class:
[Java]
package barcodemysql;
public class Main {
public static void main(String[] args)
{
// for inserting and updating barcode image in MySQL DB
GenerateAndSaveBarCode sample1 = new GenerateAndSaveBarCode();
sample1.PerformInsertExample();
sample1.PerformUpdateExample();
// for fetching image from DB and recognizing codetext
FetchAndRecognizeBarCode sample2 = new FetchAndRecognizeBarCode();
sample2.PerformRecognition();
}
}