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()
鸿蒙 HarmonyOs 对相册照片、视频的压缩
最新推荐文章于 2024-11-09 17:20:28 发布