如何在React Native中将Base64字符串图像转换为Blob?

4

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

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


1
你解决了吗?怎么转换? - Abolfazl Roshanzamir
有人解决了这个问题吗? - Mehdi Faraji
1个回答

2

我的项目中有一个将图像转换为 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的输出。我必须将结果(res.uri)的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,我能让它工作吗? - Andus
是的,我也得到了相同类型的URI。你可以试一下。如果它有效,请接受答案。 - Ayesh Nipun
2
抱歉,问题是关于将base64字符串图像转换为blob(但答案似乎使用了uri)。不过,您启发了我使用uri到blob的转换,最终我使用了https://dev59.com/-qjka4cB1Zd3GeqPHPwd来实现。非常感谢您的帮助。 - Andus
这个答案代码返回了 {"_h": 0, "_i": 0, "_j": null, "_k": null} 并且不起作用。 - Mehdi Faraji

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接