Shanuka
Shanuka

Reputation: 23

React native create a custom folder and save photos using react-native-crop-picker android

I'm using react-native-image-crop-picker. I want to save the photos to the gallery or to a custom folder taken from the camera using react-native-image-crop-picker. Normally the photos taken from the react-native-image-crop-picker are saved in the cache folder. I want to change it to a custom folder and display the images in the gallery with an auto-generated name like the first photo - p1.jpg, second photo - p2.jpg, Is there any way to implement it.

const takePhotoFromCamera = () => {
        ImagePicker.openCamera({
            width: 300,
            height: 400,
            cropping: true,
            includeBase64: true,
            freeStyleCropEnabled: true,
            compressImageQuality: 0,
            enableRotationGesture: true,
          }).then(image => {
            console.log(image);
          });
          
        console.warn('Take photo');
     }

react-native-image-crop-picker this is what i used

Upvotes: 0

Views: 1733

Answers (1)

ZFloc Technologies
ZFloc Technologies

Reputation: 4635

You can achieve that by using rn-fetch-blob - writeFile method

Below is a sample functons to achieve above combining both react-native-image-crop-picker and rn-fetch-blob

import {PermissionsAndroid} from 'react-native';
import ImagePicker from 'react-native-image-crop-picker';
import RNFetchBlob from 'rn-fetch-blob';

const imageCropper = () => {
  ImagePicker.openCamera({
    cropping: true,
    mediaType: 'photo',
    includeBase64: true,
  }).then((imageData) => {
    const base64Data = imageData.data;
    const fileName = getUniqueFileName('jpg');
    writeFileToStorage(base64Data, fileName);
  });
};

const getUniqueFileName = (fileExt) => {
  //It is better naming file with current timestamp to achieve unique name
  var d = new Date();
  var year = d.getFullYear();
  var month = d.getMonth() + 1;
  var date = d.getDate();
  var hour = d.getHours();
  var minute = d.getMinutes();
  var fileName = 'IMG' + year + month + date + hour + minute + '.' + fileExt;
  return fileName;
};

const writeFileToStorage = async (base64Data, fileName) => {
  try {
    const result = await PermissionsAndroid.request(WRITE_EXTERNAL_STORAGE);
    if (result == PermissionsAndroid.RESULTS.GRANTED) {
      const dirs = RNFetchBlob.fs.dirs;
      var folderPath = dirs.SDCardDir + '/Custom Folder/';
      var fullPath = folderPath + fileName;

      RNFetchBlob.fs.mkdir(folderPath).then((res) => {
        console.log('res', res);
      });

      RNFetchBlob.fs.writeFile(fullPath, base64Data, 'base64').then((res) => {
        console.log('file saved :', res);
      });
    } else {
      console.log('Permission Not Granted');
    }
  } catch (err) {
    console.log(err);
  }
};

Upvotes: 1

Related Questions