鴻蒙開發過程中,經常會進行系統調用,拍照、拍視頻、選擇圖庫圖片、選擇圖庫視頻、選擇文件。今天就給大家分享一個工具類。
1.話不多說,先展示樣式
2.設計思路
根據官方提供的指南開發工具類,基礎的拍照、拍視頻、圖庫選照片、選文件不過多綴述,圖庫選擇這里設計成集合形式,可返回圖片和視頻,視頻展示時不顯示內容,所以在工具類多加了一個獲取視頻縮略圖的功能。
![搜狗高速瀏覽器截圖20240326151450.png](//file1.elecfans.com/web2/M00/C5/D1/wKgZomYChGOAUaiiAADe1d8SeRY102.jpg)
**3.具體代碼**
import common from '@ohos.app.ability.common';
import picker from '@ohos.file.picker';
import mediaLibrary from '@ohos.multimedia.mediaLibrary';
import wantConstant from '@ohos.ability.wantConstant';
import { MediaBean } from '../bean/MediaBean';
import { StringUtils } from '../utils/StringUtils';
/**
- @description 多媒體輔助類
- @author Gwei
- @time 2024/3/1 15:57
*/
export class MediaHelper {
private readonly TAG: string = 'MediaHelper';
private mContext: common.Context;
constructor(context: common.Context) {
this.mContext = context;
}
/**
- 圖庫選擇,返回最大數量為9的圖片、視頻集合
*/
public selectPicture(count:number): Promise< Array< MediaBean >> {
let imgList:Array< string > = [];
let mediaList:Array< MediaBean > = [];
try {
let photoSelectOptions = new picker.PhotoSelectOptions();
photoSelectOptions.MIMEType = picker.PhotoViewMIMETypes.IMAGE_TYPE;
photoSelectOptions.maxSelectNumber = 9-count;
let photoPicker = new picker.PhotoViewPicker();
return photoPicker.select(photoSelectOptions)
.then((photoSelectResult) = > {
//Log.info(this.TAG, 'PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(photoSelectResult));
if (photoSelectResult && photoSelectResult.photoUris && photoSelectResult.photoUris.length > 0) {
for (let i = 0; i < photoSelectResult.photoUris.length; i++) {
imgList.push(photoSelectResult.photoUris[i]);
}
//Log.info(this.TAG, 'PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + filePath);
return imgList;
}
}).catch((err) = > {
//Log.error(this.TAG, 'PhotoViewPicker.select failed with err: ' + err);
return err;
}).then(async (imgList) = > {
for (let index = 0; index < imgList.length; index++) {
const mediaBean = await this.buildMediaBean(imgList[index]);
mediaList.push(mediaBean);
}
return mediaList;
});
} catch (err) {
//Log.error(this.TAG, 'PhotoViewPicker failed with err: ' + err);
return Promise.reject(err);
}
}
/**
選擇文件
*/
public selectFile(): Promise< MediaBean > {
try {
let documentSelectOptions = new picker.DocumentSelectOptions();
let documentPicker = new picker.DocumentViewPicker();
return documentPicker.select(documentSelectOptions)
.then((documentSelectResult) = > {
//Log.info(this.TAG, 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + JSON.stringify(documentSelectResult));if (documentSelectResult && documentSelectResult.length > 0) { let filePath = documentSelectResult[0]; //Log.info(this.TAG, 'DocumentViewPicker.select successfully, DocumentSelectResult uri: ' + filePath); return filePath; }
}).catch((err) = > {
//Log.error(this.TAG, 'PhotoViewPicker.select failed with err: ' + err);
return err;
}).then(async (filePath) = > {const mediaBean = await this.buildMediaBean(filePath); return mediaBean;
});
} catch (err) {
//Log.error(this.TAG, 'PhotoViewPicker failed with err: ' + err);
return Promise.reject(err);
}
}
/**
- 拍照
*/
public async takePhoto(context: common.UIAbilityContext): Promise< MediaBean > {
let want = {
'uri': '',
'action': wantConstant.Action.ACTION_IMAGE_CAPTURE,
'parameters': {},
};
return context.startAbilityForResult(want)
.then((result) = > {
//Log.info(this.TAG, `startAbility call back , ${JSON.stringify(result)}`);
if (result.resultCode === 0 && result.want && StringUtils.isNotNullOrEmpty(result.want.uri)) {
//拍照成功
//Log.info(this.TAG, 'takePhoto successfully, takePhotoResult uri: ' + result.want.uri);
return result.want.uri;
}
}).catch((error) = > {
//Log.info(this.TAG, `startAbility error , ${JSON.stringify(error)}`);
return error;
}).then(async (uri: string) = > {
const mediaBean = await this.buildMediaBean(uri);
return mediaBean;
});
}
/**
- 拍視頻
*/
public async takeVideo(context: common.UIAbilityContext): Promise< MediaBean > {
let want = {
'uri': '',
'action': wantConstant.Action.ACTION_VIDEO_CAPTURE,
'parameters': {},
};
return context.startAbilityForResult(want)
.then((result) = > {
//Log.info(this.TAG, `startAbility call back , ${JSON.stringify(result)}`);
if (result.resultCode === 0 && result.want && StringUtils.isNotNullOrEmpty(result.want.uri)) {
//拍照成功
//Log.info(this.TAG, 'takePhoto successfully, takePhotoResult uri: ' + result.want.uri);
return result.want.uri;
}
}).catch((error) = > {
//Log.info(this.TAG, `startAbility error , ${JSON.stringify(error)}`);
return error;
}).then(async (uri: string) = > {
const mediaBean = await this.buildMediaBean(uri);
return mediaBean;
});
}
/**
- 封裝多媒體實體類
- @param uri 文件路徑
*/
private async buildMediaBean(uri: string): Promise< MediaBean > {
if (StringUtils.isNullOrEmpty(uri)) {
return null;
}
const mediaBean: MediaBean = new MediaBean();
mediaBean.localUrl = uri;
await this.appendFileInfoToMediaBean(mediaBean, uri);
return mediaBean;
}
/**
- 通過Uri查找所選文件信息,插入到MediaBean中
- @param mediaBean
- @param uri
*/
private async appendFileInfoToMediaBean(mediaBean: MediaBean, uri: string):Promise< MediaBean > {
if (StringUtils.isNullOrEmpty(uri)) {
return;
}
let fileList: Array< mediaLibrary.FileAsset > = [];
const parts: string[] = uri.split('/');
const id: string = parts.length > 0 ? parts[parts.length - 1] : '-1';
try {
let media = mediaLibrary.getMediaLibrary(this.mContext);
let mediaFetchOptions: mediaLibrary.MediaFetchOptions = {
selections: mediaLibrary.FileKey.ID + '= ?',
selectionArgs: [id],
uri: uri
};
let fetchFileResult = await media.getFileAssets(mediaFetchOptions);
//Log.info(this.TAG, `fileList getFileAssetsFromType fetchFileResult.count = ${fetchFileResult.getCount()}`);
fileList = await fetchFileResult.getAllObject();
fetchFileResult.close();
await media.release();
} catch (e) {
//Log.error(this.TAG, "query: file data exception ");
}
if (fileList && fileList.length > 0) {
let fileInfoObj = fileList[0];
//Log.info(this.TAG, `file id = ${JSON.stringify(fileInfoObj.id)} , uri = ${JSON.stringify(fileInfoObj.uri)}`);
//Log.info(this.TAG, `file fileList displayName = ${fileInfoObj.displayName} ,size = ${fileInfoObj.size} ,mimeType = ${fileInfoObj.mimeType}`);
mediaBean.fileName = fileInfoObj.displayName;
mediaBean.fileSize = fileInfoObj.size;
mediaBean.fileType = fileInfoObj.mimeType;
mediaBean.pixelmap = await this.getPixelmap(fileInfoObj)
}
}
/**
- @description 獲取縮略圖
- @author Gwei
- @time 2024/3/1 15:57
*/
getPixelmap(fileInfoObj) {
return new Promise(function (resolve, reject) {
fileInfoObj.getThumbnail((err, pixelmap) = > {
if (!err) {
resolve(pixelmap)
}else{
resolve('');
}
})
})
}
}
**4.使用方法**
async handleClick(option: MediaOption) {
let mediaBean: MediaBean;
switch (option) {
case MediaOption.TakePhoto:
mediaBean = await this.mediaHelper.takePhoto(getContext() as common.UIAbilityContext);
this.imgList.push(mediaBean)
break;
case MediaOption.TakeVideo:
mediaBean = await this.mediaHelper.takeVideo(getContext() as common.UIAbilityContext);
this.imgList.push(mediaBean)
break;
case MediaOption.Picture:
let list: Array< MediaBean > = [];
list = await this.mediaHelper.selectPicture(this.imgList.length);
for (let i = 0; i < list.length; i++) {
this.imgList.push(list[i])
}
break;
case MediaOption.File:
mediaBean = await this.mediaHelper.selectFile();
this.audioList.push(mediaBean);
break;
default:
break;
}
}
工具類已經提供給大家了,希望能幫助到大家!!!
審核編輯 黃宇
-
鴻蒙
+關注
關注
57文章
2321瀏覽量
42749
發布評論請先 登錄
相關推薦
評論