One of the features I commonly see requested for Android applications is QR code reader or barcode internal integration. some native Android applications actually use an external application for QR code/barcode scanning. that, as far as I know, is not an option at the moment in air on Android. however, thanks to the open source zxing library, some direction from Amer dababneh and a blog post by Michael B, I was able to create basic sample flex-based mobile application that accessed the camera and read QR codes. this blog post will show you how.
For any smart asses out there (Yes, I mean you Ray)-Yes, I can still code. It's just been a while since I had something "blogworthy ."
Create your project
To begin with, of course, you need to create your new Flex mobile project-I used a standard view-based application. I shoshould note that while I only tested this on Android (via my Nexus One ), it's entirely possible that this code will work as is on iOS or BlackBerry tablet OS via the recent flash builder 4.5.1 update.
The important thing to note here is that you will need to enable camera permissions in your app. XML file. this can be done during the new project wizard or by manually adding the below items to your app. XML within the android "manifestadditions" section:
<Uses-Permission Android: Name ="Android. Permission. Camera"/>
<Uses-feature Android: Name ="Android. Hardware. Camera. autofocus"/>
In my experience, if you forget to do this or don't do it properly, the camera will simply fail silently (which can lead to needless debugging frustration-so just don't forget ).
Adding the camera
Now that we 've created our new Flex mobile application, we need to lay out our sample application. my sample is very simple with only a home view that contains the camera, a label to display any results and a button to start the process and capture the QR codes. for reference, I borrowed some of the camera placement code from this blog post by Guillaume.
You can see the visual elements of the page laid out below. The spritevisualelement is the container that will hold the view to our camera.
"100%" horizontalalign = "center" id = "VG"
"SV" width = "360" Height = "400" />
"LBL" text = "" />
"BTN" label = "Start camera" width = "220" Height = "93" click = "button#clickhandler (Event) "/>
the first time the user clicks the button, it will start the camera. inside my click handler for the button, I have the following code that first gets an instance of the camera, attaches it to a videodisplay object which is added as a child to our spritevisualelement. we also initialize our qrcodereader class which is from the zxing library.
If (camera. issupported)
{< br> camera = camera. getcamera ();
camera. setmode ( 360 , 360 , 24 );
videodisplay. X = 360;
Sv. addchild (videodisplay);
videodisplay. attachcamera (CAMERA);
videodisplay. rotation = 90;
qrreader = new qrcodereader;
BTN. label = "scan now" ;
LBL. TEXT = "" ;
camerastarted = true;
}< br> else {
LBL. TEXT = "no camera found" ;< BR >}
If you ran your app right now (see the full code at the end of this post for all the necessary variables and imports) you wocould see a view into your device's camera appear once you click the button to start-that is if our qrcodereader wasn't throwing compile errors. let's get those fixed.
Modifying the zxing Library
Obviusly, in order to create this project you must download the zxing library from Google Code. simply dump the library into your "SRC" folder where it shoshould be under a COM. google. zxing package. as I noted, you will get some complile errors as soon as you try to use the necessary files for qrcodescanning. luckily they are very easy to correct as they all involve unnecessary or missing imports.
Here are the changes required to get this working on our project:
- In qrcodemultireader add import COM. google. zxing. binarybitmap; (or just press Ctrl + space after the binarybitmap on the line with the compile error and have flash builder Add the import for you);
- In decoderresult comment out import of MX. Controls. List;
- In bufferedimageluminancesource comment out import MX. Controls. image;.
Reading the QR code
Most of the zxing library usage code to read the QR code was taken verbatim from the blog post by Michael B referenced above. the decodesnapshot method, which is triggered when the user presses the button to capture a QR code, gets the bitmap data from the camera and passes it to the decodebitmapdata method. the decodebitmapdata method mostly handles passing this bitmap data to the zxing library for decoding and then displaying the result in the label. the getallhints method actually tells the zxing library what kind of QR/barcode we are trying to decode. theoretically, if you wanted to decode other standard Barcode types, you woshould just add those to the hashtable. zxing supports polictypes of barcode scanning and if you simply add the other types, it shoshould just work-but I emphasize shoshould because I didn't test it yet.
Public Function decodesnapshot (): void
{
LBL. Text = "Checking ..." ;
BMI = new bitmapdata ( 300 , 300 );
BMI. Draw (videodisplay, null, true );
Videodisplay. cacheasbitmap = true;
Videodisplay. cacheasbitmapmatrix = new matrix;
Decodebitmapdata (BMI, 300 , 300 );
BMI. Dispose ();
BMI = NULL;
System. GC ();
}
Public Function decodebitmapdata (bmp d: bitmapdata, width: int, height: INT): void
{
VaR lsource: bufferedimageluminancesource = new bufferedimageluminancesource (bmp d );
VaR bitmap: binarybitmap = new binarybitmap (New globalhistogrambinarizer (lsource ));
VaR ht: hashtable = NULL;
Ht = This. getallhints ();
VaR Res: Result = NULL;
Try {
Res = qrreader. Decode (bitmap, HT );
}
Catch (Event: Error ){
}
If (RES = NULL ){
Videodisplay. Clear ();
LBL. Text = "Nothing decoded" ;
}
Else {
VaR parsedresult: parsedresult = resultparser. parseresult (RES );
LBL. Text = parsedresult. getdisplayresult ();
Sv. removechild (videodisplay );
Camerastarted = false;
BTN. Label = "Start camera" ;
}
}
Public Function getallhints (): hashtable
{
VaR ht: hashtable = new hashtable;
Ht. Add (decodehinttype. possible_formats, barcodeformat. qr_code );
Return HT;
}
testing your QR code reading
for testing, I used this QR code generator for encode both URL and straight text encoded QR codes. in my tests, not only did the QR code reading work well but it ran pretty fast (and my Nexus One is no powerhouse any longer-if it ever was ). one thing I did note though is that it can be pretty picky about where the QR code is placed within the image. it shoshould be centered and shoshould not be so close that it takes up the entire camera. I think this is partly because we are actually passing only a 300x300 bitmap out of our 360x360 camera image to be decoded, so this might be fixable. if that isn't correctable in that manner than I thought it wocould be wise to add some guides as an overlay to help the user know where to align the QR code.
The other thing I noticed was that when I created a timer event and tested checked the camera periodically using that (as in the linked sample I sourced ), I did get some performance issues where the app periodically became unusable (mostly during debugging mode but it seemed indicative of a problem you 'd want to potentially eliminate ).
That's it. Not too complicated eh? For reference, below is the finished flex mobile view with all the elements you need to get this sample running. let me know if this helps you or if you manage to expand upon the example (and feel free to share your code if you do ).
P.s. I am not posting an fxp because I am unsure if there are any redistribution restrictions on the license for zxing.
<? XML version = "1.0" Encoding = "UTF-8" ?>
<S: View xmlns: FX =Http://ns.adobe.com/mxml/2009"Xmlns: MX ="Library: // ns.adobe.com/flex/mx"
Xmlns: S ="Library: // ns.adobe.com/flex/spark"Title ="Homeview">
<FX: declarations>
<! -- Place non-visual elements (e.g., services, value objects) Here -->
</FX: declarations>
<FX: SCRIPT>
<! [CDATA [
Import com. Google. zxing. barcodeformat;
Import com. Google. zxing. binarybitmap;
Import com. Google. zxing. bufferedimageluminancesource;
Import com. Google. zxing. decodehinttype;
Import com. Google. zxing. result;
Import com. Google. zxing. Client. Result. parsedresult;
Import com. Google. zxing. Client. Result. resultparser;
Import com. Google. zxing. Common. bitmatrix;
Import com. Google. zxing. Common. bytematrix;
Import com. Google. zxing. Common. globalhistogrambinarizer;
Import com. Google. zxing. Common. flexdatatypes. hashtable;
Import com. Google. zxing. qrcode. qrcodereader;
Import com. Google. zxing. qrcode. detector. detector;
Import spark. Events. viewnavigatorevent;
Protected var camera: camera;
Private var videodisplay: Video = new video ( 360 , 360 );
Private var qrreader: qrcodereader;
Private var BMI: bitmapdata;
Private var camerastarted: Boolean = false;
Protected function button#clickhandler (Event: mouseevent): void
{
If (! Camerastarted ){
If (camera. issupported)
{
Camera = camera. getcamera ();
Camera. setmode ( 360 , 360 , 24 );
Videodisplay. x = 360;
Sv. addchild (videodisplay );
Videodisplay. attachcamera (CAMERA );
Videodisplay. Rotation = 90;
Qrreader = new qrcodereader;
BTN. Label = "Scan now" ;
LBL. Text = "" ;
Camerastarted = true;
}
Else {
LBL. Text = "No camera found" ;
}
}
Else {
Decodesnapshot ();
}
}
Public Function decodesnapshot (): void
{
LBL. Text = "Checking ..." ;
BMI = new bitmapdata ( 300 , 300 );
BMI. Draw (videodisplay, null, true );
Videodisplay. cacheasbitmap = true;
Videodisplay. cacheasbitmapmatrix = new matrix;
Decodebitmapdata (BMI, 300 , 300 );
BMI. Dispose ();
BMI = NULL;
System. GC ();
}
Public Function decodebitmapdata (bmp d: bitmapdata, width: int, height: INT): void
{
VaR lsource: bufferedimageluminancesource = new bufferedimageluminancesource (bmp d );
VaR bitmap: binarybitmap = new binarybitmap (New globalhistogrambinarizer (lsource ));
VaR ht: hashtable = NULL;
Ht = This. getallhints ();
VaR Res: Result = NULL;
Try {
Res = qrreader. Decode (bitmap, HT );
}
Catch (Event: Error ){
}
If (RES = NULL ){
Videodisplay. Clear ();
LBL. Text = "Nothing decoded" ;
}
Else {
VaR parsedresult: parsedresult = resultparser. parseresult (RES );
LBL. Text = parsedresult. getdisplayresult ();
Sv. removechild (videodisplay );
Camerastarted = false;
BTN. Label = "Start camera" ;
}
}
Public Function getallhints (): hashtable
{
VaR ht: hashtable = new hashtable;
Ht. Add (decodehinttype. possible_formats, barcodeformat. qr_code );
Return HT;
}
]>
</FX: SCRIPT>
<S: vgroup width ="100%"Horizontalalign ="Center"Id ="VG">
<S: spritevisualelement id ="SV"Width ="360"Height ="400"/>
<S: Label id ="LBL"TEXT =""/>
<S: button id ="BTN"Label ="Start camera"Width ="220"Height ="93"Click ="Button#clickhandler (event )"/>
</S: vgroup>
</S: View>
Http://remotesynthesis.com/post.cfm/adding-a-qr-code-reader-in-flex-on-android