HarmonyOS开发之使用PhotoViewPicker(图库选择器)保存图片

一:效果图

二:添加依赖

复制代码
import fs from '@ohos.file.fs';//文件管理
import picker from '@ohos.file.picker'//选择器

三:下载,保存图片的实现

复制代码
// 下载图片imgUrl
 downloadAndSaveImage(imgUrl: string) {
    http.createHttp()
      .request(imgUrl,
        (error, data: http.HttpResponse) => {
          if (error) {
            promptAction.showToast({
              message: '下载失败',
              duration: 2000
            })
            return
          }
          if (data.result instanceof ArrayBuffer) {
            this.pickerSave(data.result as ArrayBuffer)
          }
        })
  }

//保存图片
  async pickerSave(buffer: ArrayBuffer): Promise<void> {
    const photoSaveOptions = new picker.PhotoSaveOptions() // 创建文件管理器保存选项实例
    photoSaveOptions.newFileNames = ['PhotoView' + new Date().getTime() + '.jpg']//创建一个开头为PhotoView_xxxx_.jpg的图片
    const photoViewPicker = new picker.PhotoViewPicker
    photoViewPicker.save(photoSaveOptions)
      .then(async (photoSaveResult) => {
        let uri = photoSaveResult[0]
        let file = await fs.open(uri, fs.OpenMode.READ_WRITE | fs.OpenMode.CREATE)
        await fs.write(file.fd, buffer)
        await fs.close(file.fd)
        promptAction.showToast({
          message: "保存成功"
        })
      })
      .catch(error => {
        console.log('downloadAndSaveImage  保存失败:', error)
        promptAction.showToast({
          message: "保存失败"
        })
      })
  }

四:在Page中的使用

复制代码
@Entry
@Component
struct ImgPage {
  @State imageUrl: string =""

  aboutToAppear(){
    const params = router.getParams()
    if (params) {
     this.imageUrl = params['imageUrl']//https:xxxxxx.png
      if (!this.imageUrl) {
        console.error("imageUrl 加载失败: imageUrl 为空");
      }
    }

  }

  build() {
    Column() {
      Stack().height(30)
      HeadlineBar({
        title:"详情",
        heightBar: 45,
        fontSize:20,
        closeCallback: () => {
          router.back()
        }
      })
      // 显示每个图片
      Image(this.imageUrl)
        .alt($r('app.media.icon'))// 使用alt,在网络图片加载成功前使用占位图
        .width(300)
        .height(400)
        .margin({top:30})
        .borderRadius(8)

      Button('立即下载')
        .fontSize(15)
        .width(131)
        .height(54)
        .margin({
          top:30
        })
        .onClick(()=>{
          if (this.imageUrl) {
            weatherApi.downloadAndSaveImage(this.imageUrl)
          }
        })

    }
    .width('100%')
    .height('100%')
  }
}
相关推荐
花椒技术2 天前
HJPusher / HJPlayer SDK 实践:我们为什么把直播推播链路拆成一套可复用能力
设计模式·harmonyos·直播
一维Ace2 天前
HarmonyOS ArkTS 按钮组件全解:Button、Toggle 状态交互实战
harmonyos
anyup3 天前
来简单聊聊鸿蒙开发,万元奖金的事~
前端·华为·harmonyos
Georgewu3 天前
【无测试机别害怕】华为云鸿蒙云手机南:从零到联调全流程详解
harmonyos
Georgewu3 天前
【HarmonyOS 7】DevEco Code安装与使用
harmonyos
Georgewu4 天前
【HarmonyOS 7】鸿蒙应用开发如何屏蔽剪切板
harmonyos
谷子在生长5 天前
纯血鸿蒙自定义弹窗最佳实践:从「到处复制」到「一行调用」
前端·harmonyos
小魔女千千鱼5 天前
把 Go 塞进鸿蒙PC:windows上用 c-shared 跑 2048
harmonyos
TrisighT5 天前
Electron 跑在鸿蒙 PC 上,单窗口和多窗口内存差 800MB?我抓了 5 组数据
性能优化·electron·harmonyos