【问题标题】:React-Native: Convert image url to base64 stringReact-Native:将图像 url 转换为 base64 字符串
【发布时间】:2016-04-26 18:27:34
【问题描述】:

我正在构建一个 react native 应用程序,它需要以 base64 字符串格式存储图像以提供离线查看功能。

什么库/函数会给我最好的结果来将图像存储为 base64 字符串?假设我的网址是“http://www.example.com/image.png”。

另外,在将其存储为字符串之前,我是否需要发出 http 请求才能获取它?我的逻辑说是的,但是在本机反应中,您可以在 组件上加载图像,而无需先从服务器请求它们。

在本机反应中执行此操作的最佳选择是什么?

【问题讨论】:

    标签: javascript image base64 react-native


    【解决方案1】:
    If You are using **react-native-image-picker**
    Then it includes base64 string in response object
    
        if you are  using any  other library i.e. **react-native-document-picker**
        then you have to use **react-native-fs** library 
        
        import RNFS from 'react-native-fs';
        
          RNFS.readFile(item.uri, 'base64').then((res) => {
                      //Here in enter code here res you  will get base64 string 
                    });
    
      
    

    【讨论】:

      【解决方案2】:
      import { Platform, ActionSheetIOS } from 'react-native';
      import DocumentPicker from 'react-native-document-picker';
      import ImagePicker from 'react-native-image-crop-picker';
      import RNFS from 'react-native-fs';
      

      对于文档转换:

        pickDocument = async (resolve: (payload: any) => void, reject: (payload: any) => void) => {
          try {
            const result = await DocumentPicker.pick({
              type: [DocumentPicker.types.images, DocumentPicker.types.pdf]
            });
            const fileType = result[0].type;
            const fileExtension = fileType.substr(fileType.indexOf('/') + 1);
            const realURI = Platform.select({ android: result[0].uri, ios: decodeURI(result[0].uri), })
            const b64 = await RNFS.readFile(realURI, "base64")
            const filename = result[0].name.replace(/\s/g, '')
            resolve({ b64, fileType, fileExtension, filename });
          } catch {
            reject(new Error('Action cancelled!'));
          }
        }
      

      图片转换:

        pickImage = (resolve: (payload: any) => void, reject: (payload: any) => void) => {
          ImagePicker.openPicker({
            width: 300,
            height: 400,
            cropping: true,
          }).then(async response => {
            const { path: b64Content, mime: fileType, filename:name } = response;
            const b64 = await RNFS.readFile(b64Content, "base64")
            const fileExtension = String(fileType).substr(String(fileType).indexOf('/') + 1);
            const filename = name.replace(/\s/g, '')
            resolve({ b64, fileType, fileExtension, filename });
          }).catch(({message})=>{
            console.log('ERROR',message)
            reject(new Error('Action cancelled!'));
          });
        }
      

      【讨论】:

        【解决方案3】:

        如果您在托管工作流中使用 expo 并且无法使用 react-native-fs,您可以使用 expo-file-system 库来实现。这是一个辅助函数,它只提供一个图像 URL 并返回一个 base64 编码的图像。 PS:不包含base64前缀,需要根据自己的图片类型自行包含。

        
        import * as FileSystem from 'expo-file-system';
        
        
        async function getImageToBase64(imageURL) {
          let image;
        
          try {
            const { uri } = await FileSystem.downloadAsync(
              imageURL,
              FileSystem.documentDirectory + 'bufferimg.png'
            );
        
            image = await FileSystem.readAsStringAsync(uri, {
              encoding: 'base64',
            });
          } catch (err) {
            console.log(err);
          }
        
          return image;
        }
        

        React Native Image 组件中的一个示例用法如下:

        <Image
          style={{ width: 48, height: 48 }}
          source={{ uri: `data:image/png;base64,${image}` }}
        />
        

        【讨论】:

          【解决方案4】:

          我用rn-fetch-blob,基本上它提供了很多文件系统和网络功能,使传输数据变得非常容易。

          react-native-fetch-blob 已弃用

          import RNFetchBlob from "rn-fetch-blob";
          const fs = RNFetchBlob.fs;
          let imagePath = null;
          RNFetchBlob.config({
            fileCache: true
          })
            .fetch("GET", "http://www.example.com/image.png")
            // the image is now dowloaded to device's storage
            .then(resp => {
              // the image path you can use it directly with Image component
              imagePath = resp.path();
              return resp.readFile("base64");
            })
            .then(base64Data => {
              // here's base64 encoded image
              console.log(base64Data);
              // remove the file from storage
              return fs.unlink(imagePath);
            });
          

          来源Project Wiki

          【讨论】:

          • 如何使用像'user/Project/example.png'这样的本地图片?。
          • @Sathya 文档在此处提供了带有本地文件的此类示例github.com/wkh237/react-native-fetch-blob/wiki/…
          • @OliverDixon 所以不好,因为它不适合你?
          • 其实这段代码会让app崩溃,导致FileUriExposedException
          • CocoaPods 找不到 pod "React/Core" 的兼容版本:在 Podfile 中:react-native-fetch-blob(来自 ../node_modules/react-native-fetch-blob)被解析为 0.10.6,这取决于跨度>
          【解决方案5】:

          您可以使用react-native-image-base64。您必须提供图片 url,它会返回图片的 base64 字符串。

          ImgToBase64.getBase64String('file://youfileurl')
            .then(base64String => doSomethingWith(base64String))
            .catch(err => doSomethingWith(err));
          

          【讨论】:

          • [!] CocoaPods 找不到 pod "React/Core" 的兼容版本:在 Podfile 中:react-native-fetch-blob(来自 ../node_modules/react-native-fetch-blob)被解析为 0.10.6,这取决于在 React/Core 上,您的规范源都不包含满足依赖项的规范:React/Core。您有: * 过时的源代码库,您可以使用 pod repo updatepod install --repo-update 进行更新。 * 输入错误的名称或版本。 * 未将托管 Podspec 的源代码库添加到您的 Podfile。
          【解决方案6】:

          对我来说,将 devies 上的本地文件中的 mp4 文件上传到 Facebook 或其他社交网站:

          var data = await RNFS.readFile( `file://${this.data.path}`, 'base64').then(res => { return res });
                  const shareOptions = {
                      title: 'iVideo',
                      message: 'Share video',
                      url:'data:video/mp4;base64,'+ data,
                      social: Share.Social.FACEBOOK,
                      filename: this.data.name , // only for base64 file in Android 
                  };     
                  Share.open(shareOptions).then(res=>{
                     Alert.alert('Share Success`enter code here`!')
                  }).catch(err=>{
                      console.log('err share', err);
                  });
          

          【讨论】:

            【解决方案7】:

            我使用了另一个包:react-native-fs

            import RNFS from 'react-native-fs';
            
            var data = await RNFS.readFile( "file://path-to-file", 'base64').then(res => { return res });
            

            这很好用。

            【讨论】:

              【解决方案8】:

              独立的 expo FileSystem 包使这变得简单:

              const base64 = await FileSystem.readAsStringAsync(photo.uri, { encoding: 'base64' });
              

              截至 2019 年 9 月 27 日,此软件包同时处理 file://content:// uri 的

              【讨论】:

              • 以上代码仅适用于图片,不适用于 pdf 和其他文件。
              【解决方案9】:

              react-native-image-picker 在返回的对象中包含一个 base64 数据节点。仅供参考

              【讨论】:

              • 非常感谢。我只知道我已经使用过的库。 @zematdev
              【解决方案10】:

              有一个更好的方法: 如果您还没有,请安装此 react-native-fs

              import RNFS from 'react-native-fs';
              
              RNFS.readFile(this.state.imagePath, 'base64')
              .then(res =>{
                console.log(res);
              });
              

              【讨论】:

              • 在 RN 0.63.3 上工作
              • 当我尝试保存到变量中时,它保存为[object Object] 而不是 base64 字符串。如何将base64字符串保存到变量中?
              • 它说“在命令行,在您的项目文件夹中,键入:react-native link react-native-fs。完成!无需担心手动将库添加到您的项目中。”并且然后它说Android使用情况和所有这些东西?请更新文档
              【解决方案11】:
               ImageEditor.cropImage(imageUrl, imageSize, (imageURI) => {
                    ImageStore.getBase64ForTag(imageURI, (base64Data) => {
                        // base64Data contains the base64string of the image
                    }, (reason) => console.error(reason));
               }, (reason) => console.error(reason));
              

              【讨论】:

              • React Native 警告开发人员不要再使用 ImageEditor:警告:ImageStore 已弃用,将在未来的版本中删除。要从本地图像中获取 base64 编码的字符串,请使用以下任一第三方库:* expo-file-system:readAsStringAsync(filepath, 'base64')* react-native-fs:readFile(filepath, 'base64')
              【解决方案12】:

              要在 React native 中将图像转换为 base64,FileReader 实用程序很有帮助:

              const fileReader = new FileReader();
              fileReader.onload = fileLoadedEvent => {
                const base64Image = fileLoadedEvent.target.result;
              };
              fileReader.readAsDataURL(imagepath); 
              

              这需要react-native-file

              另一种选择,也可能是首选的选择,是使用 NativeModules。 Medium article 显示了如何。它需要创建一个native module

              NativeModules.ReadImageData.readImage(path, (base64Image) => {
                // Do something here.
              });
              

              【讨论】:

                猜你喜欢
                • 2020-06-01
                • 2019-07-12
                • 2022-10-17
                • 2019-10-03
                • 2020-12-22
                • 2021-01-28
                • 2018-09-07
                • 2014-07-21
                • 1970-01-01
                相关资源
                最近更新 更多