React Native Gallery scan
The SDK allows you to decode barcodes from image files. It supports several image formats, including BMP, PNG, and JPG.
1. Gallery - To utilize this feature, pass the picture as a base64 encoded string to scanImage of the barkoder instance that onBarkoderViewCreated gave you (the General example keeps it in state). Pictures read best with the rigorous decoding speed: in onBarkoderViewCreated, call _barkoder.setDecodingSpeed(Barkoder.DecodingSpeed.rigorous);
if (!barkoder) return;
barkoder.scanImage(base64Image, (result) => {
// use the result: result.decoderResults
});
2. Add image picker (in a yarn project: yarn add react-native-image-picker):
npm install react-native-image-picker
3. Import:
import { launchImageLibrary } from 'react-native-image-picker';
4. Use: add a scanImagePressed() method to your component, next to the General example's code (it uses its barkoder state), and call it from a button, for example <Button title="Scan a picture" onPress={scanImagePressed} />. It opens the image picker (on Android the system photo picker, which needs no permission), gets the picture as base64 and sends it to the decoder:
async function scanImagePressed() {
if (!barkoder) return;
try {
launchImageLibrary(
{ mediaType: 'photo', includeBase64: true },
(response) => {
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.errorCode) {
console.error('Image Picker Error:', response.errorMessage);
} else if (response.assets?.[0]?.base64) {
const base64Image = response.assets[0].base64;
barkoder.scanImage(base64Image, (result) => {
// use the result
});
} else {
console.error('No valid image selected');
}
}
);
} catch (error) {
console.error('Error launching image library:', error);
}
}