【问题标题】:How do I convert base64 string image to blob in React Native?如何在 React Native 中将 base64 字符串图像转换为 blob?
【发布时间】:2019-10-03 14:27:34
【问题描述】:

我正在尝试使用React-Native-Camera 捕获图像并上传到服务器,捕获的响应仅提供base64 图像和系统缓存的相对uri 路径。我曾经使用 blob-util 之类的包将图像转换为网站中的 blob,这在 React-native 上不起作用。

当我四处搜索时,我发现大多数人都将 base64 字符串直接上传到服务器,但我找不到任何关于 blob 的信息,如何从 base64 图像字符串中获取 blob?

【问题讨论】:

  • 你解决了吗?如何转换?
  • 有没有人解决这个问题

标签: react-native


【解决方案1】:

我的项目中有一个函数可以将图像转换为 blob。这里是。第一个功能是处理相机。第二个功能是创建一个 blob 和一个图像名称。

addPicture = () => {
        ImagePicker.showImagePicker({ title: "Pick an Image", maxWidth: 800, maxHeight: 600 }, res => {
            if (res.didCancel) {
                console.log("User cancelled!");
            } else if (res.error) {
                console.log("Error", res.error);
            } else {
                this.updateProfilePicture(res.uri)
            }
        });
    }

这个addPicture 用于启动图像选择器。在上述函数中,res 表示来自showImagePicker 的输出。我必须将结果的uri 属性(res.uri)传递给下面的函数,以便创建 blob 文件

在下面的函数中,我想用 userId 命名图像。你可以使用任何你喜欢的东西。

updateProfilePicture = async (uri) => {
        var that = this;
        var userId = this.state.user.uid
        var re = /(?:\.([^.]+))?$/;
        var ext = re.exec(uri)[1];

        this.setState({
            currentFileType: ext
        });

        const blob = await new Promise((resolve, reject) => {
            const xhr = new XMLHttpRequest();
            xhr.onload = function () {
                resolve(xhr.response);
            };
            xhr.onerror = function (e) {
                console.log(e);
                reject(new TypeError('Network request failed'));
            };
            xhr.responseType = 'blob';
            xhr.open('GET', uri, true);
            xhr.send(null);
        });

        var filePath = userId + '.' + that.state.currentFileType;

    }

上述函数中还有一些其他代码,用于将图像上传到 Firebase 存储。我没有包含这些代码。

【讨论】:

  • 我的 uri 是由 react-native-camera 生成的,看起来像 file:///var/mobile/Containers/Data/Application/79977D77-88EC-4E6E-BAE1-09D2EEA28EDB/Library/Caches/Camera/01BAA2AD-3335-4492-853C-DC63FCB0A419.jpg,看起来不像是普通的 uri,我可以让它与它一起使用吗?
  • 是的。我也得到了相同类型的 URI。你可以试试。如果它有效,请接受答案。
  • 对不起,但问题是关于 base64 字符串 img 到 blob(但看起来答案是使用 uri)。但是,您启发了我使用 uri 进行 blob 传输,最终我使用了 https://stackoverflow.com/questions/48747278/is-it-possible-to-get-the-binary-data-from-an-image-in-react-native 来实现这一目标。谢谢你。
  • 这个答案码返回了`{"_h": 0, "_i": 0, "_j": null, "_k": null}`并且不起作用
猜你喜欢
  • 2021-01-28
  • 2016-04-26
  • 2020-06-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-22
  • 2021-02-01
  • 1970-01-01
  • 2020-09-22
相关资源
最近更新 更多