reactnative保存图片到相册

本文介绍了在ReactNative应用中如何处理安装的camera-roll库,包括判断图片是本地文件还是网络图片,以及如何使用CameraRollAPI分别对两者进行保存到相册的操作。
摘要由CSDN通过智能技术生成

安装camera-roll

npm install @react-native-camera-roll/camera-roll --save

判断是本地文件还是网络图片

    const isLocalFile = (path) => {
        // 本地文件路径的常见前缀
        const localFilePrefixes = ['file://', '/'];

        // 检查文件路径是否以本地文件前缀开始
        for (const prefix of localFilePrefixes) {
            if (path.startsWith(prefix)) {
                return true; // 是本地文件
            }
        }

        // 如果不是本地文件前缀开头,则可能是网络文件
        return false;
    };

保存图片

  const saveToCameraRoll = async (imageUrl) => {
        setIsLoading(true);
        const {config, fs} = RNFetchBlob;
        if(isLocalFile(imageUrl)) {
            // 使用 CameraRoll 保存图片到相册
            CameraRoll.saveToCameraRoll(imageUrl, 'photo')
                .then(() => {
                    EasyToast.show('图片已成功保存到相册', 1000)
                    setIsLoading(false)
                })
                .catch((error) => {
                    EasyToast.show('图片保存失败', 1000)
                    setIsLoading(false)
                });
            return
        }

        try {
            // 下载网络图片到本地
            const response = await RNFetchBlob.config({
                fileCache: true,
                appendExt: 'png', // 可以根据需要更改文件扩展名
            }).fetch('GET', imageUrl);

            const imagePath = response.path();

            // 将本地图片保存到相册
            const result = await CameraRoll.saveToCameraRoll(imagePath);
            if (result) {
                setIsLoading(false)
                EasyToast.show('图片已成功保存到相册', 1000)

            } else {

                setIsLoading(false)
                EasyToast.show('图片保存失败', 1000)
            }
        } catch (error) {
            // EasyToast.show('图片保存失败', 1000)
            setIsLoading(false)
        }
    };
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值