鸿蒙 HarmonyOs 对相册照片、视频的压缩

import { Permissions } from '@kit.AbilityKit'
import { dataSharePredicates } from '@kit.ArkData'
import { photoAccessHelper } from '@kit.MediaLibraryKit'
import { permissionManager } from '.'
import { KILO_BYTE } from '../common/utils'
import { image } from '@kit.ImageKit'
import { fileIo } from '@kit.CoreFileKit'

//清理工具
class CleanerManager {
  // 权限
  private permissions: Permissions[] = ["ohos.permission.READ_IMAGEVIDEO", "ohos.permission.WRITE_IMAGEVIDEO"]
  // 图片资源
  private photoAssets: photoAccessHelper.PhotoAsset[] = []
  // 图片字段
  private columns: photoAccessHelper.PhotoKeys[] = [
    photoAccessHelper.PhotoKeys.DATE_ADDED,
    photoAccessHelper.PhotoKeys.SIZE,
  ]
  //获取相册管理
  private phAccessHelper = photoAccessHelper.getPhotoAccessHelper(getContext(this))

  // 图片权限
  async requestPermissions() {
    await permissionManager.requestPermissions(this.permissions)
    await permissionManager.openPermissionSetting(this.permissions)
  }

  // 获取图片/视频
  async getAssets() {
    let res = await this.phAccessHelper.getAssets({
      fetchColumns: this.columns,
      predicates: new dataSharePredicates.DataSharePredicates()
    })
    let photoAssets = await res.getAllObjects()
    return photoAssets
  }

  // 获取屏幕截图列表
  async getScreenshotList() {
    let list = await this.getAssets()
    return list.filter(item => item.displayName.includes('screenshot'))
  }

  // 获取视频列表
  async getVideoList() {
    let list = await this.getAssets()
    return list.filter(item => item.photoType === photoAccessHelper.PhotoType.VIDEO)
  }

  //筛选出大图(用于压缩)
  async getLargeSizeList() {
    let list = await this.getAssets()
    return list.filter(item => (item.get(photoAccessHelper.PhotoKeys.SIZE) as number) > 200 *KILO_BYTE )
  }

  // 删除图片
  async deletePhotos(uris: string[]) {
    let list = await this.getAssets()
    let photoAssets = list.filter(item => uris.includes(item.uri))
    await photoAccessHelper.MediaAssetChangeRequest.deleteAssets(getContext(this),photoAssets)
  }

  // 压缩图片
  async compressPhoto(uri: string,quality = 50) {
    let originFile = fileIo.openSync(uri,fileIo.OpenMode.READ_ONLY)
    let imageSource = image.createImageSource(originFile.fd)
    let arrayBuffer = await image.createImagePacker().packing(imageSource,{format: 'image/jpeg',quality})
    let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(getContext(this))
    let accessUri = await phAccessHelper.createAsset(photoAccessHelper.PhotoType.IMAGE,'jpg')
    let file = fileIo.openSync(accessUri,fileIo.OpenMode.READ_WRITE)
    fileIo.writeSync(file.fd,arrayBuffer)
    fileIo.closeSync(file.fd)
  }
}

export const cleanerManager = new CleanerManager()

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值