HarmonyOS 鸿蒙Next photoAccessHelper

HarmonyOS 鸿蒙Next photoAccessHelper showAssetsCreationDialog方法无法显示保存图片的缩略图

在图片获取用户是否保存的弹窗时,无法显示图片的缩略图

3 回复

可参考如下核心demo

Index.ets:

Button('保存网络图片到应用沙盒')
    .width('100%')
    .height(40)
    .fontSize(16)
    .fontWeight(FontWeight.Bold)
    .fontColor(Color.White)
    .onClick(async () => {
      console.debug(`image => 保存网络图片到应用沙盒`)
      let dirPath = this.context.filesDir
      let fileName = 'temp2.jpg'
      if (fileIo.accessSync(`${dirPath}/${fileName}`)) {
        fileIo.rmdirSync(`${dirPath}/${fileName}`)
      }

      try {
        let result: SaveImageResultVo = await SaveImageUtil.saveImageToApplication(
          `http://gips0.baidu.com/it/u=3602773692,1512483864&fm=3028&app=3028&f=JPEG&fmt=auto?w=960&h=1280`
          , dirPath, fileName
        )
        if (0 == result.errorCode) {
          // 图片保存成功
          console.debug(`image => 保存图片到应用沙盒成功`)
          SaveImageUtil
            .saveImageToAlbum(`${dirPath}/${fileName}`)
            .then(result => {
              if (result) {
                console.debug(`image => 保存图片到相册成功`)
              } else {
                console.debug(`image => 用户拒绝授权`)
              }
            })
            .catch(error => {
              console.error('image => 保存图片到相册异常:')
            })
        }
      } catch (err) {
        console.error(err, 'image => 保存图片到应用沙盒异常:')
      }
    })

SaveImageUtil.ets:

/**
 * 保存图片工具类
 */
import { BusinessError, request } from '@kit.BasicServicesKit'
import { common } from '@kit.AbilityKit'
import { buffer } from '@kit.ArkTS'
import { fileIo as fs, fileUri } from '@kit.CoreFileKit'
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import { FileUtil } from './FileUtil'

/**
 * 保存文件到应用沙箱
 * @param image 图片url或base64
 * @param dirPath 保存文件夹路径
 * @param fileName 保存文件名
 */
async saveImageToApplication(image: string, dirPath: string, fileName: string): Promise<SaveImageResultVo> {
  return new Promise(async (resolve: Function, reject: Function) => {
    if (!fs.accessSync(dirPath)) {
      fs.mkdirSync(dirPath)
    }
    if (image.startsWith('http')) {
      // 如果是网络图片,则下载图片
      try {
        request
          .downloadFile(this.context, { url: image, filePath: `${dirPath}/${fileName}` })
          .then(downloadTask => {
            console.debug(`image => 保存图片到应用沙盒`)
            downloadTask
              .on('complete', () => {
                console.info('complete')
                // 图片下载完成
                let vo = new SaveImageResultVo
                vo.errorCode = 0
                resolve(vo)
              })
            downloadTask
              .on('fail', (err: number) => {
                let vo = new SaveImageResultVo
                vo.errorCode = err
                resolve(vo)
              })
          })
          .catch(error => {
            reject(error)
          })
      } catch (err) {
        reject(err)
      }
    } else {
      // base64图片
      let content = image
      if (image.startsWith('data:')) {
        // 如果是data:,则截取,后的数据
        content = image.split(',')[1]
      }
      try {
        const decodeBuff = buffer.from(content, 'base64').buffer
        FileUtil.writeBufferToFile(dirPath,fileName,decodeBuff)
        let vo = new SaveImageResultVo
        vo.errorCode = 0
        resolve(vo)
      } catch (err) {
        reject(err)
      }
    }
  })
}

/**
 * 保存图片到相册
 * @param path 图片路径
 * @param title 标题
 * @param extension 文件扩展名
 * @returns
 */
async saveImageToAlbum(path: string, title?: string, extension?: string): Promise<boolean> {
  return new Promise(async (resolve: Function, reject: Function) => {
    try {
      let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(this.context)
      console.info('path',path)
      let srcFileUri: Array<string> = [fileUri.getUriFromPath(path)]
      console.info(`图片 uri is : ${JSON.stringify(srcFileUri)}`)
      let photoCreationConfigs: Array<photoAccessHelper.PhotoCreationConfig> = [
        {
          title: title ? title : '保存图片',
          fileNameExtension: extension ? extension : 'jpg',
          photoType: photoAccessHelper.PhotoType.IMAGE,
          subtype: photoAccessHelper.PhotoSubtype.DEFAULT
        }
      ]
      let desFileUris: Array<string> = await phAccessHelper.showAssetsCreationDialog(srcFileUri, photoCreationConfigs)
      console.info(`目标图片 uri is : ${JSON.stringify(desFileUris)}`)
      if (desFileUris.length > 0) {
        for (let index = 0; index < desFileUris.length; index++) {
          FileUtil.copyFileContentTo(srcFileUri[index], desFileUris[index])
        }
        resolve(true)
      } else {
        resolve(false)
      }
    } catch (err) {
      reject(err)
    }
  })
}
export class SaveImageResultVo {
  errorCode: number = 0
}

export default new SaveImageUtil()

更多关于HarmonyOS 鸿蒙Next photoAccessHelper的实战系列教程也可以访问 https://www.itying.com/category-93-b0.html


你的FileUtil呢,

图片

针对帖子标题“HarmonyOS 鸿蒙Next photoAccessHelper”的问题,以下是我基于鸿蒙系统的专业知识进行的回答:

HarmonyOS鸿蒙系统中的“Next photoAccessHelper”可能是一个与照片访问相关的辅助工具或组件。在鸿蒙系统中,这类组件通常用于管理应用对照片库的访问权限,以确保用户数据的安全性和隐私保护。

具体来说,“photoAccessHelper”可能提供了以下功能:

  1. 权限管理:它可能负责请求、检查和更新应用对照片库的访问权限。
  2. 照片筛选:根据用户的设定或应用的需求,它可能帮助应用筛选符合特定条件的照片。
  3. 性能优化:在处理大量照片数据时,它可能通过缓存、索引等技术提高访问效率。

然而,由于“Next”这一前缀的具体含义不明,它可能表示这是“photoAccessHelper”的一个新版本,或者是一个特定于某个应用或功能的变体。

如果你在使用鸿蒙系统时遇到了与“Next photoAccessHelper”相关的问题,可能是由于权限设置不当、系统更新导致的兼容性问题或其他原因。建议检查应用的权限设置,并确保你的鸿蒙系统已更新到最新版本。

如果问题依旧没法解决请联系官网客服,官网地址是: https://www.itying.com/category-93-b0.html

回到顶部