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%')
  }
}
相关推荐
huang_xiaoen8 小时前
鸿蒙手机远程控制电脑哪个好用?2026鸿蒙远控软件横测推荐
华为·harmonyos·远程工作·远程工具·远程办公
爱写Bug的浮游2 天前
初识仓颉:5 分钟看懂核心语法
harmonyos·编程语言
羽落•无痕(苏晗默)2 天前
华为数通IA——14、网络服务与应用:TCP/UDP 传输层协议与 FTP、Telnet、SSH 实践
网络·网络协议·tcp/ip·网络安全·华为·udp·信息与通信
程序猿追2 天前
鸿蒙 PC 的 Ionic 工单有两个错误,按下生成后光标该去哪儿
华为·harmonyos
KevinChaos2 天前
随手备忘录手记 04|HarmonyOS 7.0新特性实验:物品图鉴的加载逻辑
华为·harmonyos
Sirius_Ji3 天前
从硬解基座到字幕与滤镜链:ffmpeg-for-HarmonyOS v0.3.2
harmonyos
用户86194177207413 天前
uni-app 鸿蒙端提现点不动?我用 UTS 插件补上了微信"确认收款"
微信·harmonyos
码间留白3 天前
uni-app 鸿蒙端提现点不动?我用 UTS 插件补上了微信"确认收款"
uni-app·harmonyos·鸿蒙·uts插件·微信商家转账
GitCode官方3 天前
开源鸿蒙跨平台直播|AI 时代,用 cj-tauri 开发鸿蒙 PC 应用
人工智能·华为·harmonyos·atomgit
程序猿追3 天前
鸿蒙 PC 用 Tauri 做本地查找,怎样让慢请求给新请求让路
华为·状态模式·harmonyos