Skip to content

Instantly share code, notes, and snippets.

@felipeslongo
Last active June 9, 2022 16:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save felipeslongo/48c0f8833bb26b3bc1481fee804aab54 to your computer and use it in GitHub Desktop.
Save felipeslongo/48c0f8833bb26b3bc1481fee804aab54 to your computer and use it in GitHub Desktop.
Android Barcode Scanner with Camera1 + MLKit
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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"
tools:context=".Camera1Activity">
<SurfaceView
android:id="@+id/preview_view"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</androidx.constraintlayout.widget.ConstraintLayout>
package com.felipeslongo.mlbarcodescanner
import android.graphics.ImageFormat
import android.hardware.Camera
import android.os.Bundle
import android.util.Log
import android.view.SurfaceHolder
import android.view.SurfaceView
import android.widget.Toast
import androidx.appcompat.app.AppCompatActivity
import com.google.mlkit.vision.barcode.BarcodeScanner
import com.google.mlkit.vision.barcode.BarcodeScanning
import com.google.mlkit.vision.common.InputImage
class Camera1Activity : AppCompatActivity() {
var cameraView: SurfaceView? = null
var camera: Camera? = null
override fun onCreate(savedInstanceState: Bundle?) {
Log.e("Camera1Activity", "ENTROU AQUI")
super.onCreate(savedInstanceState)
// Thread.sleep(4000)
setContentView(R.layout.activity_camera1)
cameraView = findViewById(R.id.preview_view)
val barcodeScanner: BarcodeScanner = BarcodeScanning.getClient()
cameraView!!.holder.addCallback(object : SurfaceHolder.Callback {
override fun surfaceCreated(surfaceHolder: SurfaceHolder) {
camera = Camera.open(Camera.CameraInfo.CAMERA_FACING_FRONT)
camera!!.setDisplayOrientation(90)
camera!!.setPreviewDisplay(surfaceHolder)
camera!!.setPreviewCallback { bytes, camera ->
val parameters = camera.parameters
val inputImage = InputImage.fromByteArray(
bytes,
parameters.previewSize.width,
parameters.previewSize.height,
90,
ImageFormat.NV21 //ImageFormat.YV12
)
barcodeScanner.process(inputImage)
.addOnSuccessListener { barcodes ->
barcodes.forEach {
Toast.makeText(this@Camera1Activity, it.rawValue, Toast.LENGTH_SHORT).show()
}
}
.addOnFailureListener {
Toast.makeText(this@Camera1Activity, it.toString(), Toast.LENGTH_SHORT).show()
}.addOnCompleteListener {
}
}
}
override fun surfaceChanged(surfaceHolder: SurfaceHolder, p1: Int, p2: Int, p3: Int) {
camera!!.startPreview();
}
override fun surfaceDestroyed(surfaceHolder: SurfaceHolder) {
camera!!.apply {
stopPreview()
release()
}
camera = null
}
})
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment