reactnative保存图片到相册-CSDN博客

阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

安装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)
        }
    };
阿里云国内75折 回扣 微信号:monov8
阿里云国际,腾讯云国际,低至75折。AWS 93折 免费开户实名账号 代冲值 优惠多多 微信号:monov8 飞机:@monov6

“reactnative保存图片到相册-CSDN博客” 的相关文章