Question

I want to implement standalone scanner in my android application.I'm using zxing's core.jar library in my project.

I need to decode a barcode from camera preview.But i don't know how to implement it.Because there is no official documentation.

Can you provide me a simple example on followings things? 1.Initialize the camera and getting preview. 2.Decode the barcode from preview.

or

Is there any example project to do this?

Was it helpful?

Solution

Take a look at my simple implementation: https://github.com/piobab/code-scanner

I use ZBar library but if you want you can change ZBarScannerView.java implementation to ZXingScannerView (the rest of the code is ok):

public class ZXingScannerView extends ScannerView {
public interface ResultHandler {
    public void handleResult(Result result);
}

private MultiFormatReader mMultiFormatReader;
private ResultHandler mResultHandler;

public ZXingScannerView(Context context) {
    super(context);
    setupScanner(null);
}

public ZXingScannerView(Context context, AttributeSet attributeSet) {
    super(context, attributeSet);
    setupScanner(null);
}

/**
 * Specify recognized codes types.
 * @param codeTypes list of codes types from ZXing library
 */
public void setCodeTypes(List<com.google.zxing.BarcodeFormat> codeTypes) {
    setupScanner(codeTypes);
}

private void setupScanner(List<com.google.zxing.BarcodeFormat> symbols) {
    Map<DecodeHintType,Object> hints = new EnumMap<DecodeHintType,Object>(DecodeHintType.class);
    // Add specific formats
    hints.put(DecodeHintType.POSSIBLE_FORMATS, symbols);
    mMultiFormatReader = new MultiFormatReader();
    mMultiFormatReader.setHints(hints);
}

/**
 * Register callback in order to receive data from scanner.
 * @param resultHandler
 */
public void setResultHandler(ResultHandler resultHandler) {
    mResultHandler = resultHandler;
}

@Override
public void onPreviewFrame(byte[] data, Camera camera) {
    Camera.Parameters parameters = camera.getParameters();
    Camera.Size size = parameters.getPreviewSize();
    int width = size.width;
    int height = size.height;

    Result rawResult = null;
    PlanarYUVLuminanceSource source = buildLuminanceSource(data, width, height);

    if(source != null) {
        BinaryBitmap bitmap = new BinaryBitmap(new HybridBinarizer(source));
        try {
            rawResult = mMultiFormatReader.decodeWithState(bitmap);
        } catch (ReaderException re) {

        } catch (NullPointerException npe) {

        } catch (ArrayIndexOutOfBoundsException aoe) {

        } finally {
            mMultiFormatReader.reset();
        }
    }

    if (rawResult != null) {
        stopCamera();
        if(mResultHandler != null) {
            mResultHandler.handleResult(rawResult);
        }
    } else {
        camera.setOneShotPreviewCallback(this);
    }
}

public PlanarYUVLuminanceSource buildLuminanceSource(byte[] data, int width, int height) {
    Rect rect = getFramingRectInPreview(width, height);
    if (rect == null) {
        return null;
    }
    // Go ahead and assume it's YUV rather than die.
    PlanarYUVLuminanceSource source = null;

    try {
        source = new PlanarYUVLuminanceSource(data, width, height, rect.left, rect.top,
                rect.width(), rect.height(), false);
    } catch(Exception e) {
    }

    return source;
}

}

If you use gradle add 'com.google.zxing:core:2.2' to your dependencies.

OTHER TIPS

You can use Zxing library, these steps assume that u are using Android studio

1- go to https://github.com/zxing/zxing and get the latest code.

2- extract the zip file, and import the android folder as a module

3- in the generated build.gradle for the imported module, change

apply plugin: 'com.android.application'

to

apply plugin: 'com.android.library'

4- in the same file remove the second line from the following section:

defaultConfig {
    applicationId "com.google.zxing.client.android"

5- go to http://repo1.maven.org/maven2/com/google/zxing/ and download the latest "android-core" and "android-integration" jars and add them in the libs folder of the android module

6- Add Dependency from your module to the android module

7- new your module is ready to use ZXing as a library and call its CaptureActivity , this is simple here, create a new activity with the following XML and Java code

Java code:

package bestteam.barcode;

import android.app.Activity;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import com.google.zxing.client.android.CaptureActivity;
import com.google.zxing.client.android.Intents;

public class MainActivity extends Activity implements View.OnClickListener, android.content.DialogInterface.OnClickListener {
private TextView tvScanResults;
private TextView tvStatus;
private Button btnScan;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    HandleClick hc = new HandleClick();
    tvScanResults = (TextView) findViewById(R.id.tvResult);
    tvStatus = (TextView) findViewById(R.id.tvStatus);
    btnScan = (Button) findViewById(R.id.butOther);
    btnScan.setOnClickListener(this);
    findViewById(R.id.butOther).setOnClickListener(hc);
}

private class HandleClick implements View.OnClickListener {
    public void onClick(View arg0) {
        Intent intent = new Intent(getApplicationContext(), CaptureActivity.class);
        intent.putExtra("SCAN_FORMATS", "QR_CODE,EAN_13,EAN_8,RSS_14,UPC_A,UPC_E,CODE_39,CODE_93,CODE_128,ITF,CODABAR,DATA_MATRIX");
        intent.setAction(Intents.Scan.ACTION);
        startActivityForResult(intent, 0);
    }
}

public void onActivityResult(int requestCode, int resultCode, Intent intent) {
    if (resultCode == Activity.RESULT_OK) {
        // Handle successful scan
        String contents = intent.getStringExtra(Intents.Scan.RESULT);
        String formatName = intent.getStringExtra(Intents.Scan.RESULT_FORMAT);
        tvStatus.setText(formatName);
        tvScanResults.setText(contents + "\n\n" + formatName);
    } else if (resultCode == Activity.RESULT_CANCELED) {
        tvStatus.setText("Press a button to start a scan.");
        tvScanResults.setText("Scan cancelled.");
    }
}


@Override
public void onClick(DialogInterface dialog, int which) {
    // TODO Auto-generated method stub
}


@Override
public void onClick(View v) {
    // TODO Auto-generated method stub
}
}

XML 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="wrap_content"
android:orientation="vertical"
tools:context=".MainActivity">

<LinearLayout
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >

<Button
    android:id="@+id/butOther"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="0.18"
    android:text="Scan"
    android:textSize="18sp" />

</LinearLayout>

<TextView android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:id="@+id/tvStatus"
android:text="Press a button to start a scan."
android:gravity="center"
android:textSize="18sp" />

<TextView
android:id="@+id/tvResult"
android:layout_width="346dp"
android:layout_height="394dp"
android:background="@android:color/white"
android:gravity="center"
android:text="Ready"
android:textColor="@android:color/black"
android:textSize="18sp" />

</LinearLayout>
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top