Demo of kbarcode finding a barcode and then the barcode parameters being printed out onto the image that the barcode was found in.
There are already a few barcode readers for Cordova. The most popular one is the official Phonegap barcode plugin, which is based on the amazingly comprehensive ZXing library of algorithms.
At FieldMotion, we were using the official plugin, but it had a few short-comings that meant we had to look for a better solution:
- When looking for a barcode, the plugin opens up an external camera application. This means that your own application stops, the external app is started, and when you find your barcode, yur app is started up again. This process is very jarring, and noticeably slow.
- You have absolutely no say over the look of the barcode scanner.
- If you want multiple barcodes, you are out of luck – you’re just going to have to go through the selection process manually for every one of them.
What we wanted was:
- A small camera view to appear when we press to select a barcode.
- To be able to style this ourselves in whatever way we want.
- To optionally keep the scanner open after it has found a barcode, so that it can keep scanning for others if need be.
- It must feel natural and fast.
So, we went looking.
In combination, these appear to be perfect – we could get images via CameraPlus, display them in a popup UI that could be used by the user to center the barcode, and then use JOB to scan the image and retrieve the code.
Unfortunately, this method is SLOW.
I identified two main reasons for this:
After some wracking of the brain, I came up with this solution:
- Tweak the CameraPlus plugin so it returns just a small image to be displayed, and also a 1px high gray-scale strip from the center of a higher-resolution image (in byte array format).
- Write a barcode decryption algorithm that will find a barcode in a 1D array of gray-scale values, instead of a 2D image.
This worked wonderfully. We now have a very usable barcode reader that is not very laggy, and finds the barcodes incredibly quickly. We’re also only interested in the EAN-13 encoding, so we don’t need to check for other encodings.
The reason we chose to use a 1D strip instead of the entire image, is that if you have a UI which has a marker displayed where you want the user to put the barcode, they are psychologically inclined to do so, so you really only need to consider that single central strip, and can safely ignore the rest of the image.
It’s a Worker, so it runs in a separate thread to the rest of your code. No need to include it in your HTML file – just correct the reference to the file in the code example below.
In the next post in this series, I’ll upload the Cordova plugin we developed to use with this.