Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Decode QR Code Image from Camera Roll React Native

I'm trying to implement a feature in my app where I the user can select a picture from their camera roll and the app will decode a QR code in the image is detected.

I'm currently using react-native-camera-roll-picker: https://github.com/jeanpan/react-native-camera-roll-picker and react-native-qrcode-local-image: https://github.com/remobile/react-native-qrcode-local-image

The problem is the local QR code image library wants me to pass a local path and isn't compatible with the native uri provided by react-native-camera-roll-picker. I would use another library for decoding the image QR code but this one appears to be the only one that works on iOS and Android and scans from existing images rather than from the actual camera.

I've also tried implementing react-native-fetch-blob in order to temporarily save the camera roll image locally, but that's been giving me trouble as well: https://github.com/wkh237/react-native-fetch-blob

This is my current attempt in a function that I call in the "callback" prop for react-native-camera-roll-picker (with previous attempts commented out):

_pickedImage(array,currentImg) {
console.log(currentImg)
var path = RNFS.DocumentDirectoryPath + '/pickedqr';
let rnfbURI = RNFetchBlob.wrap(RNFetchBlob.fs.asset(currentImg.uri))
const Blob = RNFetchBlob.polyfill.Blob
Blob.build(rnfbURI, {type:'image/jpg'}).then((b) => {
  tmpBlob = b;
  RNFetchBlob.fs.readFile(tmpBlob, 'base64').then((data) => {
    console.log("Base64", data)
    QRDecoder.decode(`data:image/gif;base64,${data}`, (error, result)=>{
      console.log("Code", result)
      console.log("Error", error)
    });
  });
})
/*fullPath = currentImg.uri.replace("assets-library://", "cdvfile://localhost/assets-library/")
QRDecoder.decode(fullPath, (error, result)=>{
  console.log("Code", result)
  console.log("Error", error)
});*/
/*let blb = Blob.build( rnfbURI, { type: 'image/jpg'})
console.log(blb)*/
/*RNFetchBlob.fs.readFile(rnfbURI, 'base64').then((data) => {
  console.log("Base64", data)
  QRDecoder.decode(`data:image/gif;base64,${data}`, (error, result)=>{
    console.log("Code", result)
    console.log("Error", error)
  });
})*/
}

I'm at a total loss at the moment so any methods or insight would be much appreciated.

like image 686
Armin Avatar asked Mar 11 '17 13:03

Armin


People also ask

How do I read a QR code from an image in react native?

You can use rn-qr-generator to decode a QR code in an image. import RNQRGenerator from 'rn-qr-generator'; RNQRGenerator. detect({ uri: PATH_TO_IMAGE, // local path of the image.

Can you open QR code from a picture?

While you can use your camera to scan QR codes that aren't on your phone, you'll need to install an app to read QR codes from existing pictures. Fortunately, the best QR code apps are free and super easy to use!


1 Answers

you can use react-native-qrcode-scanner to scan QR from images or directly through the camera.

INSTALLATION:

install dependency by using this command:

yarn add react-native-camera react-native-qr-scanner

link those libraries by using:

react-native link react-native-camera && react-native-qr-scanner

you need to add the permission to your AndroidManifest.xml of your project. This should be found in your android/app/src/main/AndroidManifest.xml Add the following:

<uses-permission android:name="android.permission.CAMERA" />
<uses-permission android:name="android.permission.RECORD_AUDIO"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.VIBRATE"/>

With iOS 10 and higher, you need to add the "Privacy - Camera Usage Description" key to the info.plist of your project. This should be found in your_project/ios/your_project/Info.plist. Add the following code:

<key>NSCameraUsageDescription</key>
<string/>
<key>NSPhotoLibraryUsageDescription</key>
<string/>
<key>NSMicrophoneUsageDescription</key>
<string/>
<key>NSPhotoLibraryAddUsageDescription</key>
<string/>

Usage:

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View, TouchableOpacity} from 'react-native';
import {QRreader} from 'react-native-qr-scanner';
import ImagePicker from 'react-native-image-picker';
 
export default class Scanner extends Component {
  constructor(props) {
    super(props);
    this.state = {
      reader: {
        message: null,
        data: null
      }
    };
  }
  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={()=>{
          this.openPhoto();
        }}>
          <Text style={{marginTop: 20}}>打开相册识别二维码</Text>
        </TouchableOpacity>
        <View>
        {!this.state.reader? <Text>{!this.state.reader.message?'':`${this.state.reader.message}`}</Text>: <Text>{!this.state.reader.message?'':`${this.state.reader.message}:${this.state.reader.data}`}</Text>}
        </View>
      </View>
    );
  }
  
  openPhoto(){
    console.log('ImagePicker');
    ImagePicker.launchImageLibrary({}, (response) => {
      console.log('Response = ', response);
    
      if (response.didCancel) {
        console.log('User cancelled image picker');
      }
      else if (response.error) {
        console.log('ImagePicker Error: ', response.error);
      }
      else if (response.customButton) {
        console.log('User tapped custom button: ', response.customButton);
      }
      else {
        if(response.uri){
          var path = response.path;
          if(!path){
              path = response.uri;
          }
          QRreader(path).then((data)=>{
            this.setState({reader: {
              message: '识别成功',
              data: data
            }});
            // 十秒后自动清空
            setTimeout(() => {
              this.setState({reader: {
                message: null,
                data: null
              }})
            }, 10000);
          }).catch((err)=>{
            this.setState({reader: {
              message: '识别失败',
              data: null
            }});
          });
          
      }
      }
    });
  }
}
const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff'
  }
});

you can read more about this library here: https://www.npmjs.com/package/react-native-qr-scanner

like image 192
Shashin Bhayani Avatar answered Oct 19 '22 12:10

Shashin Bhayani