将Base64转换为png并保存在设备中React Native Expo [英] Convert Base64 to png and save in the device React Native Expo

查看:110
本文介绍了将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-system expo-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

这是mi代码

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的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆