How to save base64 as a picture file by react native

in react native , you need to convert a piece of base64 string data into a picture and save it to an album

.

now I don"t know how to save base64 strings

the saveToCameraRoll (tag, type) provided in the CameraRoll component seen on the official website can be saved to the album
, but this method requires tag to be a local picture or video

such as file:/sdcard/img.png

on android .

encountered this pit and has been resolved. https://zhuanlan.zhihu.com/p/.
ios directly use CameraRoll

android:

//saveBase64ImageToCameraRoll.js
import RNFetchBlob from 'rn-fetch-blob';
import RNFS from 'react-native-fs';
import { Alert, Platform, CameraRoll } from 'react-native';

export default function (base64Img, success, fail) {
  
  const dirs =  Platform.OS === 'ios' ? RNFS.LibraryDirectoryPath : RNFS.ExternalDirectoryPath; // android
  const downloadDest = `${dirs}/${((Math.random() * 10000000) | 0)}.png`;
  const imageDatas = base64Img.split('data:image/png;base64,');
  const imageData = imageDatas[1];

  RNFetchBlob.fs.writeFile(downloadDest, imageData, 'base64').then((rst) => {
    try {
      CameraRoll.saveToCameraRoll(downloadDest).then((e1) => {
        console.log('suc',e1)
        success && success()
      }).catch((e2) => {
        console.log('fai',e2)
        Alert.alert('[]-[]-[]')
      })
    } catch (e3) {
      // Alert.alert(JSON.stringify(e3))
      console.log('catch',e3)
      fail && fail()
    }
  });
}


found that higher versions of android will flicker when using this
try to use RNFS, but there will be a problem, and it is still being resolved
July 13

. < hr >

just used it yesterday, just save it directly, that is, use the CameraRoll to find an article on the Internet to learn how to configure it. It's not difficult.

clipboard.png

Menu