• reactnative保存图片到相册


    安装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;
        };
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14

    保存图片

      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
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
  • 相关阅读:
    算法|Day50 单调栈1
    MyBatis
    在Linux终端中查找域名对应的IP地址
    Vue+Element-ui+SpringBoot搭建后端汽车租赁管理系统
    Kafka消息队列中关于消息的实现原理
    iOS WKWebView 判断跳转链接是否是用户点击
    大模型微调方法
    适配器模式
    肠道病毒组识别早产儿坏死性小肠结肠炎发病前的特异性病毒特征
    ABTest如何计算最小样本量-工具篇
  • 原文地址:https://blog.csdn.net/XKFC1/article/details/133855827