You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
packagecom.example.cameraapptest;
importandroid.Manifest;
importandroid.content.pm.PackageManager;
importandroid.os.Bundle;
importandroid.util.Log;
importandroid.util.Size;
importandroidx.annotation.NonNull;
importandroidx.appcompat.app.AppCompatActivity;
importandroidx.camera.core.CameraSelector;
importandroidx.camera.core.ImageAnalysis;
importandroidx.camera.core.ImageProxy;
importandroidx.camera.core.Preview;
importandroidx.camera.lifecycle.ProcessCameraProvider;
importandroidx.camera.view.PreviewView;
importcom.google.common.util.concurrent.ListenableFuture;
importcom.google.mlkit.vision.barcode.Barcode;
importcom.google.mlkit.vision.barcode.BarcodeScanner;
importcom.google.mlkit.vision.barcode.BarcodeScannerOptions;
importcom.google.mlkit.vision.barcode.BarcodeScanning;
importcom.google.mlkit.vision.common.InputImage;
importjava.nio.ByteBuffer;
importjava.util.concurrent.ExecutionException;
importjava.util.concurrent.ExecutorService;
importjava.util.concurrent.Executors;
publicclassMainActivityextendsAppCompatActivity {
privatestaticfinalintREQUEST_CODE_PERMISSIONS = 10;
privatestaticfinalStringTAG = MainActivity.class.getSimpleName();
privateExecutorServicecameraExecutor;
privatePreviewViewviewFinder;
@OverrideprotectedvoidonCreate(BundlesavedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//this view displays camera previewviewFinder = findViewById(R.id.viewFinder);
//checks for permission to either start camera or request permissionif (hasCameraPermission()) {
startCamera();
} else {
requestPermissions(newString[]{Manifest.permission.CAMERA}, REQUEST_CODE_PERMISSIONS);
}
//executor where qr code evaluation will happencameraExecutor = Executors.newSingleThreadExecutor();
}
privatebooleanhasCameraPermission() {
returncheckSelfPermission(Manifest.permission.CAMERA) == PackageManager.PERMISSION_GRANTED;
}
privatevoidstartCamera() {
ListenableFuture<ProcessCameraProvider> cameraProviderFuture = ProcessCameraProvider.getInstance(this);
cameraProviderFuture.addListener(() -> {
//this will provide for us the frames from the cameraProcessCameraProvidercameraProvider;
try {
cameraProvider = cameraProviderFuture.get();
} catch (ExecutionException | InterruptedExceptionexception) {
Log.e(TAG, "Unable to get camera provider instance", exception);
return;
}
//set the view where preview will be shownPreviewpreview = newPreview.Builder().build();
preview.setSurfaceProvider(viewFinder.createSurfaceProvider());
//use back cameraCameraSelectorcameraSelector = CameraSelector.DEFAULT_BACK_CAMERA;
//set up QR code analysisImageAnalysisimageAnalysis = newImageAnalysis.Builder().setTargetResolution(newSize(1280, 720)).build();
imageAnalysis.setAnalyzer(cameraExecutor, newQRCodeAnalyzer());
try {
cameraProvider.unbindAll();
cameraProvider.bindToLifecycle(this, cameraSelector, preview, imageAnalysis);
} catch (Exceptionexception) {
Log.e(TAG, "Use case binding failed", exception);
}
}, getMainExecutor());
}
@OverrideprotectedvoidonDestroy() {
super.onDestroy();
cameraExecutor.shutdown();
}
@OverridepublicvoidonRequestPermissionsResult(intrequestCode, @NonNullString[] permissions, @NonNullint[] grantResults) {
if (requestCode == REQUEST_CODE_PERMISSIONS) {
if (hasCameraPermission()) {
startCamera();
} else {
finish();
}
}
}
privatestaticclassQRCodeAnalyzerimplementsImageAnalysis.Analyzer {
//this is from ml kitprivateBarcodeScannerscanner;
QRCodeAnalyzer() {
BarcodeScannerOptionsoptions = newBarcodeScannerOptions.Builder().setBarcodeFormats(Barcode.FORMAT_QR_CODE).build();
scanner = BarcodeScanning.getClient(options);
}
@Overridepublicvoidanalyze(@NonNullImageProxyimage) {
//this analyze method will be called about every second and will provide a camera frame//this API is from camerax library, so with this frame we will pass along ml kit library//for it to tell us if there is any qr code in the imageByteBufferimageBuffer = image.getPlanes()[0].getBuffer();
InputImageinputImage = InputImage.fromByteBuffer(
imageBuffer,
image.getWidth(),
image.getHeight(),
image.getImageInfo().getRotationDegrees(),
InputImage.IMAGE_FORMAT_NV21
);
scanner.process(inputImage)
.addOnSuccessListener(barcodes -> {
//here we receive response from ml kit with the qr codes evaluatedfor (Barcodebarcode : barcodes) {
Log.i(TAG, "Read QR code: " + barcode.getDisplayValue());
}
if (barcodes.isEmpty()) {
Log.i(TAG, "No QR codes found");
}
})
.addOnFailureListener(e -> Log.e(TAG, "Failed to read QR code"));
image.close();
}
}
}
The text was updated successfully, but these errors were encountered:
This is an old project that no longer receives support nor works 100% as expected.
For anyone looking for a simple solution to read QR codes you can use both Android CameraX library and Google ML Kit Barcode library as such:
build.gradle
AndroidManifest.xml
activity_main.xml
MainActivity.java
The text was updated successfully, but these errors were encountered: