Convert Base64 to png and save in the device React Native Expo

I've been trying to save an image on a mobile device with React Native and Expo, i have tried with these packages:

import RNFetchBlob from 'react-native-fetch-blob';
import RNfs from 'react-native-fs ';

but both give me this error when implementing them

null is not an object (evaluating 'RNFetchBlob.DocumentDir')

then try expo-file-system but i don't see any clear example of how to convert base64 and download it to mobile

UPDATE

I was able to do it, my purpose was to save the base64 of a QR and convert it to png and at the same time be able to share it, I did it using expo-file-system and expo-sharing

this is mi code,

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);
        });
}

Actually, I don't know if it's the best way, first write a png image in the directory and then rewrite it with the base64 code, but it worked

Upvotes: 5

Views: 15162

Answers (2)

DiegoNano94
DiegoNano94

Reputation: 51

Thanks for the update. I've been struggling for days with this on Android and base64 images!

In my case i was trying to upload a base64 image from a signature pad on expo and always got "Network request failed"

I managed to make it work like this hope it helps!

  import * as FileSystem from 'expo-file-system';
  
  const uploadBase64 = async (base64String) => {

    this.setState({ uploading: true });

    //Without this the FilySystem crashes with 'bad base-64'
    const base64Data = base64String.replace("data:image/png;base64,","");

    try {
      //This creates a temp uri file so there's no neeed to download an image_source to get a URI Path
      const uri = FileSystem.cacheDirectory + 'signature-image-temp.png'
      await FileSystem.writeAsStringAsync(
          uri,
          base64Data,
          {
            'encoding': FileSystem.EncodingType.Base64
          }
      )

      //At this point the URI 'file://...' has our base64 image data and now i can upload it with no "Network request failed" or share the URI as you wish
      const uploadResult = await this.uploadImageAsync(uri).then(res => res.json())
      if (uploadResult) {
        this.setState({ image: uploadResult.location });
      }
      this.setState({ uploading: false });

    } catch (e) {
      this.setState({ uploading: false });
      console.log('*Error*')
      console.log(e)
    }
  }

  //Just and ordinary upload fetch function 
  const uploadImageAsync = (uri) => {

    let apiUrl = 'https://file-upload-example-backend-dkhqoilqqn.now.sh/upload';

    let formData = new FormData();
    formData.append('photo', {
      uri,
      name: `photo.png`,
      type: `image/png`,
    });

    let options = {
      method: 'POST',
      body: formData,
      headers: {
        Accept: 'application/json',
        'Content-Type': 'multipart/form-data',
      },
    };

    return fetch(apiUrl, options);
  }

Upvotes: 5

Santiago Ferreira
Santiago Ferreira

Reputation: 131

This worked for me:

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);

Upvotes: 13

Related Questions