Я хочу внедрить автономный сканер в свое приложение для Android. В своем проекте я использую библиотеку zxing core.jar.
Мне нужно декодировать штрих-код из предварительного просмотра камеры. Но я не знаю, как это реализовать. Потому что официальной документации нет.
Можете ли вы предоставить мне простой пример следующих вещей? 1. Инициализируйте камеру и получите предварительный просмотр. 2. Декодируйте штрих-код из предварительного просмотра.
or
Есть ли пример проекта для этого?
Ответ 1 · рейтинг 5 · piobab
Взгляните на мою простую реализацию: https://github.com/piobab/code-scanner.
Я использую библиотеку ZBar, но если вы хотите, вы можете изменить реализацию ZBarScannerView.java на ZXingScannerView (остальный код в порядке):
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;
}
}
Если вы используете gradle, добавьте "com.google.zxing:core:2.2" в свои зависимости.
Ответ 2 · рейтинг 1 · user2904625
Вы можете использовать библиотеку Zxing, эти шаги предполагают, что вы используете Android studio.
1. Перейдите на страницу https://github.com/zxing/zxing и получите последнюю версию кода.
2- распакуйте zip-файл и импортируйте папку Android как модуль
3- в сгенерированном build.gradle для импортированного модуля изменить
apply plugin: 'com.android.application'
to
apply plugin: 'com.android.library'
4- в этом же файле удалить вторую строку из следующего раздела:
defaultConfig {
applicationId "com.google.zxing.client.android"
5- перейдите на http://repo1.maven.org/maven2/com/google/zxing/ и загрузите последние jar-файлы "android-core" и "android-integration" и добавьте их в папку libs модуля android.
6. Добавьте зависимость от вашего модуля к модулю android.
7- новый ваш модуль готов использовать ZXing в качестве библиотеки и вызвать его CaptureActivity , здесь это просто, создайте новую активность со следующим кодом XML и Java
Java-код:
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-код:
<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>