Android barcode scanner and android barcode scanner

Source: Internet
Author: User

Android barcode scanner and android barcode scanner

Source code:

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

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

Reference link:

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

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

Objective: To complete a barcode scanning program, identify the one-dimensional code and two-dimensional code, and display the parsed results.


: Scanning-"scanning successful

After the scan is successful:

First, place a preview box on the layout to display the camera's shot in real time and draw a line to scan back and forth. Then, put an imageView below it to display the image obtained after the camera is automatically focused.

Implementation: the overall layout of the Activity is vertical linear layout. This linear layout is embedded with one frame layout and another linear layout. The frame layout first prevents a SurfaceView at the underlying layer, which is used to display the camera preview image, and then places a self-implemented View class ScanLineView on it, which inherits from the View class, the main function is to draw a red line for scanning back and forth on SurfaceView. In the following LinearLayout, an ImageView is placed to display the focused image (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:orientation="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:layout_width="fill_parent"            android:layout_height="fill_parent" />        <com.miao.barcodereader.ScanLineView            android:id="@+id/capture_viewfinder_view"            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:background="@android:color/transparent" />    </FrameLayout>    <LinearLayout        android:layout_width="match_parent"        android:layout_height="0px"        android:layout_weight=".7"        android:orientation="vertical" >        <ImageView            android:id="@+id/imageView"            android:layout_width="fill_parent"            android:layout_height="fill_parent"            android:src="@drawable/ic_launcher" />    </LinearLayout></LinearLayout>
ScanLineView class:

Inherits from the View class and reloads its onDraw function. The onDraw function sends a request for re-painting screen at intervals, the drawLine function is used to draw a red line that gradually increases with the abscissa each time it is called. If this class is too troublesome, you can leave it empty. just delete the ScanLineView control in the above layout file, which has no effect on the program functions.

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);paint = new Paint(Paint.ANTI_ALIAS_FLAG); }@Overridepublic void onDraw(Canvas canvas) {canvasWidth = canvas.getWidth();canvasHeight = canvas.getHeight();drawLine(canvas);postInvalidateDelayed(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:

Displays the preview image to SurfaceView and automatically focuses it at intervals. After the focus is successful, the obtained image is displayed in the ImageView control and parsed. If the resolution is successful, the result is displayed in a dialog box. In the constructor of this class, first obtain the activity, imageView, and SurfaceView controls of the main window, and then set some other parameters.

This class implements the SurfaceHolder. Callback interface. Therefore, the surfaceChanged, surfaceCreated, and surfaceDestroyed functions must be implemented. Call the initCamera function in surfaceCreated to open the camera and Preview It On SurfaceView.

This class implements a timer CameraTimerTask, which enables the camera to focus automatically at each interval when the camera is successfully turned on, and calls the automatic focus callback function mAutoFocusCallBack at the same time. This function is self-implemented. Its function is to call the preview callback function previewCallback when the focus is successful. This is also self-implemented. The function is to place the obtained preview image in ImageView, convert the image to Bitmap format, and send it to the BitmapLuminanceSource class (this class parses the image after receiving the image, returns a string type variable ). If this type of parsing is successful, the parsed bar code is returned. If the parsing fails, "empty" is returned ". In previewCallback, if the string returned by BitmapLuminanceSource is not "empty", the resolution is successful 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;private 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 = surfaceView.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);}}};previewCallback = 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.length);if (imageFormat == ImageFormat.NV21) {// get full pictureBitmap image = null;int w = parameters.getPreviewSize().width;int 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, 100, baos)) {image = BitmapFactory.decodeByteArray(baos.toByteArray(), 0, baos.size());image = adjustPhotoRotation(image, 90);imageView.setImageBitmap(image);Drawable 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(mAutoFocusCallBack);}}}@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.stopPreview();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));Display 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(90);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(bm, 0, 0, bm.getWidth(),bm.getHeight(), m, true);return bm1;} catch (OutOfMemoryError ex) {}return null;}}
Remember to write permission 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" />
The last is the BitmapLuminanceSource class:

For more information, see references.

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;public class BitmapLuminanceSource extends LuminanceSource {private byte bitmapPixels[];protected 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.bitmapPixels[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-generated catch blocke.printStackTrace();}if(result == null)return "empty";elsereturn result.toString();}}



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.