HarmonyOS鸿蒙Next中保存网络图片到相册

HarmonyOS鸿蒙Next中保存网络图片到相册

两步:

1、下载图片到本地

2、复制本地图片到相册(通过弹窗授权的方式保存到相册)

@Entry
@Component
struct saveToPhoto {
  private context: Context = getContext(this)
  private phAccessHelper = photoAccessHelper.getPhotoAccessHelper(this.context)
  pixelMap: PixelMap | undefined = undefined

  build() {
    Column() {
      Image('')
        .draggable(false)
        .gesture(
          LongPressGesture()
            .onAction(() => {
              this.dowImageAndSave('图片地址')
            })
        )
    }
  }

  dowImageAndSave(url: string) {
    let packOptions: image.PackingOption = { format: 'image/jpeg', quality: 98 }
    let imagePackerApi = image.createImagePacker()
    // 下载图片到本地
    http.createHttp().request(url, {
      method: http.RequestMethod.GET,
      connectTimeout: 60000,
      readTimeout: 60000
    }, async (error: BusinessError, data: http.HttpResponse) => {
      if (error) {
        console.log(`${error.code},${error.message}`)
      } else {
        let imageData: ArrayBuffer = data.result as ArrayBuffer
        let ImageSource: image.ImageSource = image.createImageSource(imageData)
        // 创建pixelmap对象
        this.pixelMap = await ImageSource.createPixelMap()

        const path: string = this.context.cacheDir + "/save_image.jpg"
        // 写入本地
        let file = fs.openSync(path, fs.OpenMode.CREATE | fs.OpenMode.READ_WRITE)
        await imagePackerApi.packToFile(this.pixelMap, file.fd, packOptions)

        // 获取图片uri
        let uri = fileUri.getUriFromPath(path)
        // 复制图片到相册
        try {
          let uris: Array<string> = [uri]
          let photoCreationConfig: Array<photoAccessHelper.PhotoCreationConfig> = [
            {
              title: 'dowImg',
              fileNameExtension: 'jpg',
              photoType: photoAccessHelper.PhotoType.IMAGE,
              subtype: photoAccessHelper.PhotoSubtype.DEFAULT
            }
          ]

          // 基于弹窗授权的方式获取媒体库的目标uri
          let desFileuris: Array<string> = await this.phAccessHelper.showAssetsCreationDialog(uris, photoCreationConfig)
          // 将应用沙箱的照片写入媒体库
          let desFile: fs.File = await fs.open(desFileuris[0], fs.OpenMode.WRITE_ONLY)  // 相册
          let srcFile: fs.File = await fs.open(uri, fs.OpenMode.READ_ONLY)    // 沙箱图片
          // 沙箱图片复制到相册
          await fs.copyFile(srcFile.fd, desFile.fd)
          fs.close(srcFile)
          fs.close(desFile)
        } catch (err) {
          console.log(`${err.code}, ${err.message}`)
        }
      }
    })
  }
}

更多关于HarmonyOS鸿蒙Next中保存网络图片到相册的实战教程也可以访问 https://www.itying.com/category-93-b0.html

2 回复

在HarmonyOS Next中保存网络图片到相册需要使用@ohos.file.fs@ohos.multimedia.mediaLibrary模块。首先通过http模块下载图片数据,然后使用fs将数据写入临时文件。最后通过mediaLibrarygetMediaLibrary接口获取媒体库实例,调用createAsset方法将文件保存到相册。注意需要申请ohos.permission.WRITE_MEDIA权限。代码示例:

import mediaLibrary from '@ohos.multimedia.mediaLibrary';
// 下载图片并保存逻辑

更多关于HarmonyOS鸿蒙Next中保存网络图片到相册的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


在HarmonyOS Next中保存网络图片到相册的代码实现是正确的,主要流程清晰:

  1. 下载图片部分使用@kit.NetworkKit的http模块实现网络请求,获取图片数据后通过@kit.ImageKit创建ImageSourcePixelMap对象。

  2. 本地存储部分:

  • 使用context.cacheDir获取缓存目录路径
  • 通过@kit.CoreFileKit的fileIo模块将图片写入应用沙箱
  • 使用fileUri.getUriFromPath()获取文件URI
  1. 保存到相册部分:
  • 通过photoAccessHelper.showAssetsCreationDialog()触发系统弹窗授权
  • 使用fileIo.copyFile()将沙箱文件复制到媒体库目录

代码中需要注意:

  1. 需要确保在config.json中声明了ohos.permission.READ_IMAGEVIDEOohos.permission.WRITE_IMAGEVIDEO权限
  2. 错误处理完善,对网络请求和文件操作都进行了try-catch
  3. 使用了LongPressGesture手势触发保存操作

整体实现符合HarmonyOS的文件访问规范和权限要求。

回到顶部