Android Barcode Scanning Program

Source: Internet
Author: User

Source:

Address 1:https://github.com/alivebao/barcodereader

Address 2:http://download.csdn.net/detail/miaoyunzexiaobao/8297201

Reference Links:

Zxing Getting Started: http://www.cnblogs.com/liuan/archive/2012/01/05/2312714.html

Bitmapluminancesource class implementation: http://blog.csdn.net/xyz_fly/article/details/8089558

Objective: To complete a barcode scanning program, can identify the one-dimensional code and QR code, and will be resolved to show the results


: Scan in-"Scan succeeded"

After the scan succeeds:

First, place a preview box on the layout to show real-time what the camera is shooting and draw a line back and forth to scan it. A imageview is then placed underneath it to show the image acquired after the camera auto-focus.

Implementation: The overall layout of the activity is the linear layout of the direction vertical. The linear layout is embedded with one frame layout and another linear layout. The frame layout first prevents a surfaceview at the bottom, which is used to display the camera preview picture, and then puts an own implementation of the view class Scanlineview, which inherits from view, the main function is to draw a red line back and forth on the Surfaceview. The following linearlayout places a ImageView, which is used to display the image obtained after focusing (the program automatically decodes the image)

Code

<linearlayout xmlns:android= "http://schemas.android.com/apk/res/android" xmlns:tools= "http// Schemas.android.com/tools "android:layout_width=" match_parent "android:layout_height=" Match_parent "Android:orien tation= "Vertical" tools:context= ".        Mainactivity "> <framelayout android:layout_width=" match_parent "android:layout_height=" 0px " Android:layout_weight= ". 3" > <surfaceview android:id= "@+id/preview_view" android:layou            T_width= "Fill_parent" android:layout_height= "fill_parent"/> <com.miao.barcodereader.scanlineview Android:id= "@+id/capture_viewfinder_view" android:layout_width= "Fill_parent" Android:layo ut_height= "Fill_parent" android:background= "@android: Color/transparent"/> </FrameLayout> <li         Nearlayout android:layout_width= "match_parent" android:layout_height= "0px" android:layout_weight= ". 7" Android:orientation= "vertical" > <imageview android:id= "@+id/imageview" Android:layout_wi Dth= "Fill_parent" android:layout_height= "fill_parent" android:src= "@drawable/ic_launcher"/> & Lt;/linearlayout></linearlayout>
Scanlineview class:

Inheriting from the view class, overloading its OnDraw function, sending a request to redraw the screen in the middle of the OnDraw function, the function of the DrawLine function is to draw a gradually increasing red line each time it is invoked. This class if too troublesome words can also not write, the above layout file in the Scanlineview control to delete the line, the program function has no effect.

Code

Package Com.miao.barcodereader;import Android.content.context;import Android.graphics.canvas;import Android.graphics.color;import Android.graphics.paint;import Android.graphics.rect;import Android.util.attributeset;import Android.view.view;public class Scanlineview extends view{private static final long Animation_delay = 10l;private Paint paint;private int xlinepos = 0;private int canvaswidth = 0;private int canvasHeight = 0;public Scanlineview (Context context, AttributeSet Attrs) {Super (context, attrs);p aint = new Paint (paint.anti_alias_ FLAG); } @Overridepublic void OnDraw (canvas canvas) {canvaswidth = Canvas.getwidth (); canvasheight = Canvas.getheight (); DrawLine (Canvas);p ostinvalidatedelayed (animation_delay, 0, 0, canvaswidth, canvasheight);}  private void DrawLine (canvas canvas) {int ilinebegin = Canvaswidth/5;int Ilineend = canvaswidth * 4/5;int Iframehigh = Canvasheight; Rect frame = new Rect (ilinebegin, 0, Canvaswidth, iframehigh); Xlinepos + = 10;if (Xlinepos > Ilineend) xlinepos = Ilinebegin;paint.setcolor (color.red); Canvas.drawrect (Xlinepos, 0, Xlinepos + 1, iframehigh, paint);}} 


Cameramanage class:

is responsible for displaying the preview to Surfaceview, and automatically focusing every time, after the successful focus is displayed in the ImageView control, and the image is parsed. If parsing succeeds, the result is popped up as a dialog box. In the constructor for the class, get the activity, ImageView control, and Surfaceview control of the main window, and then set up some other parameters.

This class implements the Surfaceholder.callback interface, so we implement the surfacechanged, surfacecreated, surfacedestroyed three functions. In surfacecreated, call the Initcamera function to open the camera and display its preview on the Surfaceview.

This class implements a timer Cameratimertask, which is capable of automatically focusing the camera in the case of a successful camera opening, and calls the auto-Focus callback function Mautofocuscallback while focusing. The function is implemented by itself, and its function is to invoke the preview callback function previewcallback when the focus succeeds. This is also self-fulfilling, its function is to get a preview of the image placed in ImageView, and the picture into the bitmap format, to the class Bitmapluminancesource (the class receives the picture after the image is parsed, and returns a string type variable). If the class resolves successfully, the parsed barcode content is returned and "empty" is returned if parsing fails. In Previewcallback, if the string returned by Bitmapluminancesource is not "empty", the parse succeeds and the result is displayed.

Code

Package Com.miao.barcodereader;import Java.io.bytearrayoutputstream;import Java.io.ioexception;import Java.util.timer;import Java.util.timertask;import Android.app.activity;import Android.content.Context;import Android.graphics.bitmap;import Android.graphics.bitmapfactory;import Android.graphics.imageformat;import Android.graphics.matrix;import Android.graphics.rect;import Android.graphics.yuvimage;import Android.graphics.drawable.bitmapdrawable;import Android.graphics.drawable.drawable;import Android.hardware.camera;import Android.util.log;import Android.view.display;import Android.view.SurfaceHolder; Import Android.view.surfaceview;import Android.view.windowmanager;import Android.widget.imageview;import Android.widget.toast;public class Cameramanage implements Surfaceholder.callback {private Surfaceholder Surfaceholder ;p rivate Camera camera;private activity activity; Surfaceview surfaceview;private ImageView imageview;private Timer mtimer;private timertask mtimertask;private Camera.autOfocuscallback mautofocuscallback;private Camera.previewcallback Previewcallback; Cameramanage (activity AC, ImageView IV, Surfaceview SV) {activity = Ac;imageview = Iv;surfaceview = Sv;surfaceholder = Sur Faceview.getholder (); Surfaceholder.addcallback (this); Surfaceholder.settype (Surfaceholder.surface_type_push_ buffers); Autofocusset (); mtimer = new Timer (); mtimertask = new Cameratimertask (); Mtimer.schedule (Mtimertask, 0, 500);} public void Autofocusset () {mautofocuscallback = new Camera.autofocuscallback () {@Overridepublic void Onautofocus ( Boolean success, Camera camera) {if (success) {///Isautofocus = True;camera.setoneshotpreviewcallback (Previewcallback);}}  };p reviewcallback = new Camera.previewcallback () {@Overridepublic void Onpreviewframe (byte[] data, Camera arg1) {if (data ! = null) {Camera.parameters Parameters = camera.getparameters (); int imageformat = Parameters.getpreviewformat (); LOG.I ("Map", "Image Format:" + imageformat); LOG.I ("Camerapreviewcallback", "Data length:" + data.lengthif (imageformat = = imageformat.nv21) {//Get full Picturebitmap image = Null;int W = parameters.getpreviewsize (). width;i NT H = parameters.getpreviewsize (). Height; Rect rect = new Rect (0, 0, W, h); Yuvimage img = new Yuvimage (data, imageformat.nv21, w,h, NULL); Bytearrayoutputstream BAOs = new Bytearrayoutputstream (), if (Img.compresstojpeg (rect, BAOs)) {image = Bitmapfactory . Decodebytearray (Baos.tobytearray (), 0, Baos.size ()); image = Adjustphotorotation (image, 90); Imageview.setimagebitmap (image);D rawable d = imageview.getdrawable (); bitmapdrawable BD = (bitmapdrawable) D; Bitmap BM = Bd.getbitmap (); String str = bitmapluminancesource.getresult (BM), if (!str.equals ("Empty")) Toast.maketext (Activity.getapplication () , Str,toast.length_short). Show ();}}}};} Class Cameratimertask extends TimerTask {@Overridepublic void run () {if (camera! = null) {Camera.autofocus (Mautofocuscall back);}}} @Overridepublic void surfacechanged (Surfaceholder arg0, int arg1, int arg2, int arg3) {//TODO auto-generated Method stub} @Overridepublic void Surfacecreated (Surfaceholder arg0) {//TODO auto-generated method Stubinitcamera ( Surfaceholder);} @Overridepublic void surfacedestroyed (Surfaceholder arg0) {//TODO auto-generated method stubif (camera! = null) {CAMERA.S Toppreview (); camera.release (); camera = null;} Previewcallback = Null;mautofocuscallback = null;} public void Initcamera (Surfaceholder surfaceholder) {camera = Camera.open (); if (camera = = null) {return;} Camera.parameters Parameters = Camera.getparameters (); WindowManager wm = (WindowManager) (Activity.getsystemservice (Context.window_service));D isplay Display = Wm.getdefaultdisplay (); Parameters.setpreviewsize (Display.getwidth (), Display.getheight ()); camera.setparameters (parameters); try { Camera.setpreviewdisplay (Surfaceholder);} catch (IOException e) {System.out.println (E.getmessage ());} Camera.setdisplayorientation (+); Camera.startpreview ();} Public Bitmap adjustphotorotation (Bitmap BM, final int orientationdegree) {Matrix M = new Matrix (); M.SEtrotate (Orientationdegree, (float) bm.getwidth ()/2, (float) bm.getheight ()/2); try {Bitmap bm1 = Bitmap.createbitmap (b M, 0, 0, bm.getwidth (), Bm.getheight (), M, true); return BM1;} catch (OutOfMemoryError ex) {}return null;}}
Remember to write permissions in Androidmanifest.xml:

<uses-permission android:name= "Android.permission.CAMERA"/>    <uses-feature android:name= " Android.hardware.camera "/>    <uses-feature android:name=" Android.hardware.camera.autofocus "/>
Finally, the Bitmapluminancesource class:

See reference links for ideas

Code

Package Com.miao.barcodereader;import Java.util.hashmap;import Java.util.map;import android.graphics.bitmap;import Com.google.zxing.binarizer;import Com.google.zxing.binarybitmap;import Com.google.zxing.encodehinttype;import Com.google.zxing.luminancesource;import Com.google.zxing.multiformatreader;import Com.google.zxing.notfoundexception;import Com.google.zxing.result;import Com.google.zxing.common.HybridBinarizer ;p ublic class Bitmapluminancesource extends Luminancesource {private byte bitmappixels[];p rotected Bitmapluminancesource (Bitmap Bitmap) {super (Bitmap.getwidth (), Bitmap.getheight ()); int[] data = new int[ Bitmap.getwidth () * Bitmap.getheight ()];this.bitmappixels = new Byte[bitmap.getwidth () * bitmap.getheight ()]; Bitmap.getpixels (data, 0, getwidth (), 0, 0, getwidth (), getheight ()); for (int i = 0; i < data.length; i++) {This.bitmap Pixels[i] = (byte) data[i];}} @Overridepublic byte[] Getmatrix () {return bitmappixels;} @Overridepublic byte[] GetRow (int y, byte[] row) {System.arraYcopy (bitmappixels, Y * getwidth (), row, 0, getwidth ()), return row; static public String GetResult (Bitmap Bitmap) {Multiformatreader Formatreader = new Multiformatreader (); Luminancesource Source = new Bitmapluminancesource (bitmap); Binarizer Binarizer = new Hybridbinarizer (source); Binarybitmap Binarybitmap = new Binarybitmap (Binarizer); Map hints = new HashMap (); Hints.put (Encodehinttype.character_set, "UTF-8"); Result result = Null;try {result = Formatreader.decode (Binarybitmap, hints);} catch (Notfoundexception e) {//TODO Auto-ge Nerated catch Blocke.printstacktrace ();} if (result = = null) return "EMPTY"; Elsereturn result.tostring ();}}



Android Barcode Scanning Program

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.