将 Base64 转换为 png 并保存在设备中 React Native Expo

Emm*_*nez 4 react-native expo rn-fetch-blob

我一直在尝试使用 React Native 和 Expo 在移动设备上保存图像,我尝试过这些软件包:

import RNFetchBlob from 'react-native-fetch-blob';
import RNfs from 'react-native-fs ';
Run Code Online (Sandbox Code Playgroud)

但在实现它们时都给了我这个错误

null is not an object (evaluating 'RNFetchBlob.DocumentDir')
Run Code Online (Sandbox Code Playgroud)

然后尝试 expo-file-system 但我没有看到任何清晰的示例来说明如何转换 base64 并将其下载到移动设备

更新

我能够做到这一点,我的目的是保存QR的base64并将其转换为png,同时能够共享它,我使用expo-file-system和做到了这一点expo-sharing

这是小米代码,

import * as FileSystem from 'expo-file-system';
import * as Sharing from 'expo-sharing';

//any image, I use it to initialize it

const image_source = 'https://images.unsplash.com/photo-1508138221679-760a23a2285b?ixlib=rb-1.2.1&ixid=eyJhcHBfaWQiOjEyMDd9&w=1000&q=80';

share=()=>{
  var self = this;
  self.setState({loading:true})
        FileSystem.downloadAsync(
        image_source,
        FileSystem.documentDirectory  + '.png'
      )
        .then(({ uri }) => {
          console.log(self.state.base64Code);
          FileSystem.writeAsStringAsync(
              uri,
              self.state.base64Code,
              {'encoding':FileSystem.EncodingType.Base64}
          )
          .then(( ) => {
            this.setState({loading:false})
            Sharing.shareAsync(uri);
          })

        })
        .catch(error => {
          console.error(error);
        });
}
Run Code Online (Sandbox Code Playgroud)

其实我不知道这是否是最好的方法,先在目录中写入一个png图像,然后用base64代码重写它,但它有效

小智 10

这对我有用:

const data = "data:image/png;base64,ASDFASDFASDf........"
const base64Code = data.split("data:image/png;base64,")[1];

const filename = FileSystem.documentDirectory + "some_unique_file_name.png";
await FileSystem.writeAsStringAsync(filename, base64Code, {
  encoding: FileSystem.EncodingType.Base64,
});

const mediaResult = await MediaLibrary.saveToLibraryAsync(filename);
Run Code Online (Sandbox Code Playgroud)