javascript React Native 将 base64 图像保存到相册

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48134397/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 07:49:39  来源:igfitidea点击:

React Native save base64 image to Album

javascriptandroidreact-native

提问by NamNamNam

Third Party API return a "QR code image" in base64 encode,
I need save that image to User's Album.

第三方 API 以 base64 编码返回“二维码图像”,
我需要将该图像保存到用户相册。

the React-Native-Fetch-Blob maintainer gone missing, so no one answering Github Issue, createFilefrom React-Native-Fetch-Blob Documentnot working as expected(not saving image into album)

React-Native-Fetch-Blob 维护者不见了,所以没有人回答 Github 问题, createFile来自React-Native-Fetch-Blob 文档没有按预期工作(没有将图像保存到相册中)

  import fetch_blob from 'react-native-fetch-blob';

  // json.qr variable are return from API

  const fs = fetch_blob.fs
  const base64 = fetch_blob.base64
  const dirs = fetch_blob.fs.dirs

  const file_path = dirs.DCIMDir + "/some.jpg"
  const base64_img = base64.encode(json.qr)

  fs.createFile(file_path, base64_img, 'base64')
  .then((rep) => { 
    alert(JSON.stringify(rep));
  })
  .catch((error) => {
    alert(JSON.stringify(error));
  });

Anyone deal with this problem before?

以前有人处理过这个问题吗?

How to save a base64 encode Image string to User album? (as a jpg or png file)

如何将 base64 编码的图像字符串保存到用户相册?(作为 jpg 或 png 文件)

because I fetchan API with no CORS header,
I can't debug it in Debug JS Remotely
Chrome would stop that request from happening,

因为我fetch的 API 没有 CORS 标头,
所以我无法在Debug JS Remotely
Chrome 中调试它会阻止该请求发生,

I have to run that on my Android Phone to make it work
(no CORS control on real phone)

我必须在我的 Android 手机上运行它才能使其工作
(真实手机上没有 CORS 控制)

I am planing use Clipboard save base64 string,
and hardcode it in my code,
to debug what's wrong with react-native-fetch-blobcreateFileAPI

我正在计划使用剪贴板保存 base64 字符串,
并将其硬编码到我的代码中,
以调试react-native-fetch-blobcreateFileAPI 有什么问题

采纳答案by tnyN

You can now use only react native fetch blob to achieve this.

您现在只能使用 react native fetch blob 来实现这一点。

Simply replace RNFS.writeFile with

只需将 RNFS.writeFile 替换为

RNFetchBlob.fs.writeFile(file_path, image_data, 'base64')

If you wish to view file in native OS viewer you can simply put

如果您希望在本机操作系统查看器中查看文件,您可以简单地将

                if (isAndroid) {
                  RNFetchBlob.android.actionViewIntent(file_path, 'application/pdf');
                } else {
                  RNFetchBlob.ios.previewDocument(file_path);
                }

回答by Akshay Italiya

Remove data:image/png;base64,in your base64 string

data:image/png;base64,在 base64 字符串中删除

var Base64Code = base64Image.split("data:image/png;base64,"); //base64Image is my image base64 string

const dirs = RNFetchBlob.fs.dirs;

var path = dirs.DCIMDir + "/image.png";

RNFetchBlob.fs.writeFile(path, Base64Code[1], 'base64')
.then((res) => {console.log("File : ", res)});

And then I solved my problem.

然后我解决了我的问题。

回答by NamNamNam

I solve the problem,
turn out I forgot data:image/png;base64,at beginning of the string.
enter image description here

我解决了这个问题,
结果我忘记data:image/png;base64,了字符串的开头。
在此处输入图片说明

I remove it with following code

我用以下代码删除它

  // json.qr is base64 string
  var image_data = json.qr.split('data:image/png;base64,');
  image_data = image_data[1];

and then save the image file

然后保存图像文件

  import fetch_blob from 'react-native-fetch-blob';
  import RNFS from 'react-native-fs';

  const fs = fetch_blob.fs
  const dirs = fetch_blob.fs.dirs      
  const file_path = dirs.DCIMDir + "/bigjpg.png"

  // json.qr is base64 string "data:image/png;base64,..."

  var image_data = json.qr.split('data:image/png;base64,');
  image_data = image_data[1];

  RNFS.writeFile(file_path, image_data, 'base64')
  .catch((error) => {
    alert(JSON.stringify(error));
  });

I wrote a blog about this

我写了一篇关于这个的博客

http://1c7.me/react-native-save-base64-image-to-album/

http://1c7.me/react-native-save-base64-image-to-album/

回答by Sundari Ragavan

const path = `${RNFS.PicturesDirectoryPath}/My Album`;
await RNFS.mkdir(path);
return await fetch(uri)
   .then(res => res.blob())
   .then(image => {
      RNFetchBlob.fs.readFile(uri, "base64").then(data => {
         RNFS.appendFile(`${path}/${image.data.name}`, data, "base64").catch(
            err => {
               console.log("error writing to android storage :", err);
            }
         );
      });
   });

回答by Andrey Shostik

I got this worked in following example

我在下面的例子中得到了这个

import RNFetchBlob from 'rn-fetch-blob';
import Permissions from 'react-native-permissions';

 takeSnapshot = async () => {
    const currentStatus = await Permissions.check('storage');

    if (currentStatus !== 'authorized') {
      const status = await Permissions.request('storage');

      if (status !== 'authorized') {
        return false;
      }
    }

    // put here your base64
    const base64 = '';

    const path = `${RNFetchBlob.fs.dirs.DCIMDir}/test11.png`;

    try {
      const data = await RNFetchBlob.fs.writeFile(path, base64, 'base64');
      console.log(data, 'data');
    } catch (error) {
      console.log(error.message);
    }
  };