本文介绍了将 Base64 转换为 png 并保存在设备 React Native Expo 中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在尝试使用 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')

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

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

更新

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

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

这是我的代码,

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

其实我也不知道是不是最好的办法,先在目录下写个png图片,然后用base64代码重写,但是好用

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

推荐答案

这对我有用:

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

这篇关于将 Base64 转换为 png 并保存在设备 React Native Expo 中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-24 07:02