Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
[camera] Support scanning barcode from URL (#28445)
- Loading branch information
1 parent
b92f823
commit 0a8c904
Showing
17 changed files
with
427 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
64 changes: 64 additions & 0 deletions
64
apps/native-component-list/src/screens/Camera/CameraScreenBarcodeFromURL.tsx
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,64 @@ | ||
import { BarcodeScanningResult, Camera } from 'expo-camera'; | ||
import { Image } from 'expo-image'; | ||
import * as ImagePicker from 'expo-image-picker'; | ||
import { useState } from 'react'; | ||
import { View, Text, Button, ScrollView, StyleSheet } from 'react-native'; | ||
|
||
export default function CameraScreenFromURL() { | ||
const [image, setImage] = useState<string | null>(null); | ||
const [results, setResults] = useState<BarcodeScanningResult | null>(null); | ||
|
||
const pickImage = async () => { | ||
const result = await ImagePicker.launchImageLibraryAsync({ | ||
mediaTypes: ImagePicker.MediaTypeOptions.Images, | ||
allowsEditing: false, | ||
quality: 1, | ||
}); | ||
|
||
if (!result.canceled) { | ||
setImage(result.assets[0].uri); | ||
} | ||
}; | ||
|
||
const scanImage = async () => { | ||
if (!image) { | ||
return; | ||
} | ||
const results = await Camera.scanFromURLAsync(image); | ||
setResults(results); | ||
}; | ||
|
||
return ( | ||
<View style={styles.container}> | ||
{!image && <Text>Select an image from the photo library</Text>} | ||
<Button title="Select image" onPress={pickImage} /> | ||
{image && <Image source={{ uri: image }} style={styles.image} />} | ||
{image && <Button title="Scan Image" onPress={scanImage} />} | ||
<ScrollView style={styles.scrollView} contentContainerStyle={styles.scollViewContent}> | ||
{results && <Text>{JSON.stringify(results, null, 2)}</Text>} | ||
</ScrollView> | ||
</View> | ||
); | ||
} | ||
|
||
const styles = StyleSheet.create({ | ||
container: { | ||
flex: 1, | ||
alignItems: 'center', | ||
justifyContent: 'center', | ||
gap: 20, | ||
paddingTop: 20, | ||
}, | ||
image: { | ||
width: 200, | ||
height: 200, | ||
}, | ||
scrollView: { | ||
flex: 1, | ||
width: '100%', | ||
}, | ||
scollViewContent: { | ||
padding: 20, | ||
alignItems: 'center', | ||
}, | ||
}); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
48 changes: 48 additions & 0 deletions
48
...era/android/src/main/java/expo/modules/camera/analyzers/BarcodeScannerResultSerializer.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,48 @@ | ||
package expo.modules.camera.analyzers | ||
|
||
import android.os.Bundle | ||
import android.util.Pair | ||
import expo.modules.interfaces.barcodescanner.BarCodeScannerResult | ||
|
||
object BarCodeScannerResultSerializer { | ||
fun toBundle(result: BarCodeScannerResult, density: Float) = | ||
Bundle().apply { | ||
putString("data", result.value) | ||
putString("raw", result.raw) | ||
putInt("type", result.type) | ||
val cornerPointsAndBoundingBox = getCornerPointsAndBoundingBox(result.cornerPoints, result.boundingBox, density) | ||
putParcelableArrayList("cornerPoints", cornerPointsAndBoundingBox.first) | ||
putBundle("bounds", cornerPointsAndBoundingBox.second) | ||
} | ||
|
||
private fun getCornerPointsAndBoundingBox( | ||
cornerPoints: List<Int>, | ||
boundingBox: BarCodeScannerResult.BoundingBox, | ||
density: Float | ||
): Pair<ArrayList<Bundle>, Bundle> { | ||
val convertedCornerPoints = ArrayList<Bundle>() | ||
for (i in cornerPoints.indices step 2) { | ||
val x = cornerPoints[i].toFloat() / density | ||
val y = cornerPoints[i + 1].toFloat() / density | ||
|
||
convertedCornerPoints.add(getPoint(x, y)) | ||
} | ||
val boundingBoxBundle = Bundle().apply { | ||
putParcelable("origin", getPoint(boundingBox.x.toFloat() / density, boundingBox.y.toFloat() / density)) | ||
putParcelable("size", getSize(boundingBox.width.toFloat() / density, boundingBox.height.toFloat() / density)) | ||
} | ||
return Pair(convertedCornerPoints, boundingBoxBundle) | ||
} | ||
|
||
private fun getSize(width: Float, height: Float) = | ||
Bundle().apply { | ||
putFloat("width", width) | ||
putFloat("height", height) | ||
} | ||
|
||
private fun getPoint(x: Float, y: Float) = | ||
Bundle().apply { | ||
putFloat("x", x) | ||
putFloat("y", y) | ||
} | ||
} |
102 changes: 102 additions & 0 deletions
102
...s/expo-camera/android/src/main/java/expo/modules/camera/analyzers/MLKitBarcodeAnalyzer.kt
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,102 @@ | ||
package expo.modules.camera.analyzers | ||
|
||
import android.graphics.Bitmap | ||
import android.util.Log | ||
import com.google.android.gms.tasks.Task | ||
import com.google.mlkit.vision.barcode.BarcodeScannerOptions | ||
import com.google.mlkit.vision.barcode.BarcodeScanning | ||
import com.google.mlkit.vision.barcode.common.Barcode | ||
import com.google.mlkit.vision.common.InputImage | ||
import expo.modules.interfaces.barcodescanner.BarCodeScannerResult | ||
import kotlinx.coroutines.Dispatchers | ||
import kotlinx.coroutines.suspendCancellableCoroutine | ||
import kotlinx.coroutines.withContext | ||
import kotlin.coroutines.resume | ||
import kotlin.coroutines.resumeWithException | ||
|
||
class MLKitBarCodeScanner { | ||
private var barCodeTypes: List<Int>? = null | ||
private var barcodeScannerOptions = | ||
BarcodeScannerOptions.Builder() | ||
.setBarcodeFormats(Barcode.FORMAT_ALL_FORMATS) | ||
.build() | ||
private var barcodeScanner = BarcodeScanning.getClient(barcodeScannerOptions) | ||
|
||
suspend fun scan(bitmap: Bitmap): List<BarCodeScannerResult> = withContext(Dispatchers.IO) { | ||
val inputImage = InputImage.fromBitmap(bitmap, 0) | ||
try { | ||
val result: List<Barcode> = barcodeScanner.process(inputImage).await() | ||
val results = mutableListOf<BarCodeScannerResult>() | ||
if (result.isEmpty()) { | ||
return@withContext results | ||
} | ||
for (barcode in result) { | ||
val raw = barcode.rawValue ?: barcode.rawBytes?.let { String(it) } | ||
val value = if (barcode.valueType == Barcode.TYPE_CONTACT_INFO) { | ||
raw | ||
} else { | ||
barcode.displayValue | ||
} | ||
val cornerPoints = mutableListOf<Int>() | ||
barcode.cornerPoints?.let { points -> | ||
for (point in points) { | ||
cornerPoints.addAll(listOf(point.x, point.y)) | ||
} | ||
} | ||
|
||
results.add(BarCodeScannerResult(barcode.format, value, raw, cornerPoints, inputImage.height, inputImage.width)) | ||
} | ||
return@withContext results | ||
} catch (e: Exception) { | ||
Log.e(TAG, "Failed to detect barcode: " + e.message) | ||
return@withContext emptyList() | ||
} | ||
} | ||
|
||
fun setSettings(formats: List<Int>) { | ||
if (areNewAndOldBarCodeTypesEqual(formats)) { | ||
return | ||
} | ||
val barcodeFormats = formats.reduce { acc, it -> | ||
acc or it | ||
} | ||
|
||
barCodeTypes = formats | ||
barcodeScannerOptions = BarcodeScannerOptions.Builder() | ||
.setBarcodeFormats(barcodeFormats) | ||
.build() | ||
barcodeScanner = BarcodeScanning.getClient(barcodeScannerOptions) | ||
} | ||
|
||
private fun areNewAndOldBarCodeTypesEqual(newBarCodeTypes: List<Int>): Boolean { | ||
barCodeTypes?.run { | ||
// create distinct-values sets | ||
val prevTypesSet = toHashSet() | ||
val nextTypesSet = newBarCodeTypes.toHashSet() | ||
|
||
// sets sizes are equal -> possible content equality | ||
if (prevTypesSet.size == nextTypesSet.size) { | ||
prevTypesSet.removeAll(nextTypesSet) | ||
// every element from new set was in previous one -> sets are equal | ||
return prevTypesSet.isEmpty() | ||
} | ||
} | ||
return false | ||
} | ||
|
||
companion object { | ||
private val TAG = MLKitBarCodeScanner::class.java.simpleName | ||
} | ||
} | ||
|
||
suspend fun <T> Task<T>.await(): T = suspendCancellableCoroutine { continuation -> | ||
addOnSuccessListener { result -> | ||
continuation.resume(result) | ||
} | ||
addOnFailureListener { exception -> | ||
continuation.resumeWithException(exception) | ||
} | ||
addOnCanceledListener { | ||
continuation.cancel() | ||
} | ||
} |
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.
Oops, something went wrong.
Oops, something went wrong.