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%')
  }
}
相关推荐
hqzing9 分钟前
把 glibc 移植到鸿蒙 PC 上:它能用来做什么
华为·harmonyos
OH_TPC6 小时前
HarmonyOS APP开发---“习惯猫“习惯打卡App,需要用到这个库
华为·harmonyos·鸿蒙
熊猫钓鱼>_>8 小时前
开源鸿蒙平台 KMP 三方库 kotlin-csv 适配全流程:从编码假设到沙箱真机互通验证
开发语言·人工智能·华为·kotlin·harmonyos·鸿蒙
马剑威(威哥爱编程)10 小时前
【共创稿事节】HarmonyOS 7 Agent 开发实战 09:Agent 测试评测集
华为·harmonyos
威哥爱编程12 小时前
HarmonyOS 7 Agent 开发实战 04:云端 RAG 搭企业私有知识库问答
agent·harmonyos
威哥爱编程12 小时前
HarmonyOS 7 Agent 开发实战 05:流式输出做打字机对话
agent·harmonyos
donk131412 小时前
React Native for OpenHarmony 实战:三方库 react-native-circular-action-menu 的鸿蒙化适配指南
javascript·分布式·react native·react.js·wpf·harmonyos
SuperHeroWu713 小时前
【HarmonyOS 7】 HarmonyOS 应用 Skill创建和编排详解
华为·harmonyos·开放平台·skill·小艺