小程序保存图片到相册

情景1:只有图片的远程链接
通过Taro.downloadFile将图片下载到本地,拿到临时图片路径,再通过 Taro.saveImageToPhotosAlbum将临时图片保存到相册

注意:以下代码使用的是Taro框架,如果是用原生开发,将Taro改成wx

downloadImg = () => {
    Taro.showLoading({
      title: '正在保存海报...',
      mask: true
    })
    Taro.downloadFile({
      url: 'https://profile.csdnimg.cn/4/B/D/3_jstljspservlet',
      success: (res) => {
        if (res.statusCode === 200 && res.tempFilePath) {
          let img = res.tempFilePath;
          this.savePoster(img) //  保存到相册
        } else {
          Taro.hideLoading()
          Taro.showToast({
            title: '下载海报失败',
            icon: 'success',
            duration: 2000
          })
        }
      },
      fail: (res) => {
        Taro.hideLoading()
        Taro.showToast({
          title: '下载海报失败',
          icon: 'success',
          duration: 2000
        })
      }
    });
  }

  /**
   * 保存到相册
   */
  savePoster = (url) => {
    Taro.saveImageToPhotosAlbum({
      filePath: url,
      success: (res) => {
        Taro.hideLoading()
        Taro.showModal({
          content: '海报已保存到相册',
          showCancel: false,
          confirmText: '确定',
          success: (modalRes) => {
            this.setState({
              showShareModal: false,
              showShareImgModal: false
            })
          }
        })
      },
      fail: (res) => {
        Taro.hideLoading()
        console.log('saveImageToPhotosAlbum调用失败:' + JSON.stringify(res))
        if (res && res.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || res.errMsg === "saveImageToPhotosAlbum:fail auth deny" || res.errMsg === "saveImageToPhotosAlbum:fail authorize no response"){
          Taro.showModal({
            title: '提示',
            content: '保存海报需要您配置相册权限',
            showCancel: false,
            success: () => {
              Taro.openSetting({
                success: (settingdata) => {
                  console.log(settingdata)
                  if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                    console.log("获取权限成功,再次点击图片保存到相册")
                  } else {
                    console.log("获取权限失败")
                  }
                }
              })
            }
          })
        } else {
          Taro.showToast({
            title: '保存失败',
            icon: 'error',
            duration: 2000
          })
        }
      }
    })
  }
情景2:只有图片的二进制流数据
获取二进制流数据(请求设置responseType为arraybuffer), 将二进制流数据转成base64。同时base64位数据写到文件系统的临时目录中并获取到临时图片路径,再通过 Taro.saveImageToPhotosAlbum将临时图片保存到相册
 getImgData = () => {
    // 获取图片二进制流
    request({
      url: baseUrl + `/member-service/getPng`,
      method: "get",
      header: {
        ...getJsonHead(),
        "content-type": "application/x-www-form-urlencoded"
      },
      data: {},
      responseType: 'arraybuffer',
    }, {defaultMode: false}).then(res => {
      Taro.hideLoading()
      console.log('图片流接口返回数据:', res)
      if (res && res.data) {
        let url = 'data:image/png;base64,' + Taro.arrayBufferToBase64(res.data)
        this.setState({
          posterUrl: url,
          showShareImgModal: true,
          posterBase64: Taro.arrayBufferToBase64(res.data)
        })
      } else {
        Taro.showToast({
          title: res && res.msg ? res.msg : '获取图片流失败',
          icon: 'none'
        })
      }
    }).catch(res => {
      Taro.hideLoading()
      Taro.showToast({
        title: res && res.msg ? res.msg : '获取图片流失败',
        icon: 'none'
      })
    });
  }

  writeFileInFileSystem = (type) => {
    Taro.showLoading({
      title: '正在保存海报...',
      mask: true
    })
    const number = Math.random();
    // 获取小程序的文件系统
    const fileUrl = Taro.env.USER_DATA_PATH + `/wow_poster_img_${number}.png`;  // 文件系统中的用户目录路径 (本地路径)
    const fsm = Taro.getFileSystemManager();
    // 把base64数据写入到临时目录中
    fsm.writeFile({
      filePath: fileUrl,
      data: this.state.posterBase64,
      encoding: 'base64',
      success: (res) => {
        console.log('下载图片成功返回结果:' + JSON.stringify(res))
        console.log('临时图片路径:' + fileUrl)
        this.savePoster(fileUrl, type) //  保存到相册
      },
      fail: (res) => {
        console.log('下载图片失败返回结果:' + JSON.stringify(res))
        Taro.hideLoading()
        Taro.showToast({
          title: '下载海报失败',
          icon: 'success',
          duration: 2000
        })
      }
    });
  }

  /**
   * 保存到相册
   */
  savePoster = (url) => {
    Taro.saveImageToPhotosAlbum({
      filePath: url,
      success: (res) => {
        Taro.hideLoading()
        Taro.showModal({
          content: '海报已保存到相册',
          showCancel: false,
          confirmText: '确定',
          success: (modalRes) => {
            this.setState({
              showShareModal: false,
              showShareImgModal: false
            })
          }
        })
      },
      fail: (res) => {
        Taro.hideLoading()
        console.log('saveImageToPhotosAlbum调用失败:' + JSON.stringify(res))
        if (res && res.errMsg === "saveImageToPhotosAlbum:fail:auth denied" || res.errMsg === "saveImageToPhotosAlbum:fail auth deny" || res.errMsg === "saveImageToPhotosAlbum:fail authorize no response"){
          Taro.showModal({
            title: '提示',
            content: '保存海报需要您配置相册权限',
            showCancel: false,
            success: () => {
              Taro.openSetting({
                success: (settingdata) => {
                  console.log(settingdata)
                  if (settingdata.authSetting["scope.writePhotosAlbum"]) {
                    console.log("获取权限成功,再次点击图片保存到相册")
                  } else {
                    console.log("获取权限失败")
                  }
                }
              })
            }
          })
        } else {
          Taro.showToast({
            title: '保存失败',
            icon: 'error',
            duration: 2000
          })
        }
      }
    })
  }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值