harmony 鸿蒙Selecting Media Assets Using Picker
Selecting Media Assets Using Picker
When a user needs to share files such as images and videos, use Picker to start Gallery for the user to select the files to share. No permission is required when Picker is used. Currently, a UIAbility is used to start Gallery with the window component. The procedure is as follows:
- Import modules.
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { fileIo } from '@kit.CoreFileKit';
import { BusinessError } from '@kit.BasicServicesKit';
- Create a PhotoSelectOptions instance.
const photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
- Set the type and maximum number of media files to select. The following uses images as an example. For details about the media file types, see PhotoViewMIMETypes.
photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE; // Select images.
photoSelectOptions.maxSelectNumber = 5; // Set the maximum number of images that can be selected.
- Create a photoViewPicker instance and call PhotoViewPicker.select to open Gallery for the user to select images. After the images are selected, PhotoSelectResult is returned.
let uris: Array<string> = [];
const photoViewPicker = new photoAccessHelper.PhotoViewPicker();
photoViewPicker.select(photoSelectOptions).then((photoSelectResult: photoAccessHelper.PhotoSelectResult) => {
uris = photoSelectResult.photoUris;
console.info('photoViewPicker.select to file succeed and uris are:' + uris);
}).catch((err: BusinessError) => {
console.error(`Invoke photoViewPicker.select failed, code is ${err.code}, message is ${err.message}`);
})
The permission on the URIs returned by select() is read-only. File data can be read based on the URI. Note that the URI cannot be directly used in the Picker callback to open a file. You need to define a global variable to save the URI and use a button to open the file. For details, see Reading File Data by URI.
You can also obtain an image or video based on the URI.
If metadata needs to be obtained, you can use the @ohos.file.fs and @ohos.file.fileuri APIs to obtain file attribute information, such as the file name, size, access time, modification time, and path, based on the URI.
Reading File Data by URI
- After the UI returns from Gallery, use a button to call other functions. Specifically, usefileIo.openSync to open the file and obtain its FD through the media file URI. Note that the mode parameter of fileIo.openSync() must be fileIo.OpenMode.READ_ONLY.
let uri: string = '';
let file = fileIo.openSync(uri, fileIo.OpenMode.READ_ONLY);
console.info('file fd: ' + file.fd);
- Call fileIo.readSync to read the file based on the FD, and close the FD after the data is read.
let buffer = new ArrayBuffer(4096);
let readLen = fileIo.readSync(file.fd, buffer);
console.info('readSync data to file succeed and buffer size is:' + readLen);
fileIo.closeSync(file);
Obtaining an Image or Video by URI
The media library allows Picker to select a media file URI and obtain the corresponding image or video. The following describes how to query a URI named ‘file://media/Photo/1/IMG_datetime_0001/displayName.jpg’.
import { photoAccessHelper } from '@kit.MediaLibraryKit';
import { dataSharePredicates } from '@kit.ArkData';
import { common } from '@kit.AbilityKit';
// Obtain the context from the component and ensure that the return value of this.getUiContext().getHostContext() is UIAbilityContext.
let context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
class MediaDataHandler implements photoAccessHelper.MediaAssetDataHandler<ArrayBuffer> {
onDataPrepared(data: ArrayBuffer) {
if (data === undefined) {
console.error('Error occurred when preparing data');
return;
}
console.info('on image data prepared');
// Customize the logic for processing data.
}
}
async function example() {
let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
let uri = 'file://media/Photo/1/IMG_datetime_0001/displayName.jpg' // The URI must exist.
predicates.equalTo(photoAccessHelper.PhotoKeys.URI, uri.toString());
let fetchOptions: photoAccessHelper.FetchOptions = {
fetchColumns: [photoAccessHelper.PhotoKeys.TITLE],
predicates: predicates
};
try {
let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOptions);
let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
console.info('getAssets photoAsset.uri : ' + photoAsset.uri);
// Obtain the file attribute information, such as the title. If the attribute to obtain is not a default one, add the column name to fetchColumns.
console.info('title : ' + photoAsset.get(photoAccessHelper.PhotoKeys.TITLE));
// Request image data.
let requestOptions: photoAccessHelper.RequestOptions = {
deliveryMode: photoAccessHelper.DeliveryMode.HIGH_QUALITY_MODE,
}
await photoAccessHelper.MediaAssetManager.requestImageData(context, photoAsset, requestOptions, new MediaDataHandler());
console.info('requestImageData successfully');
fetchResult.close();
} catch (err) {
console.error('getAssets failed with err: ' + err);
}
}
你可能感兴趣的鸿蒙文章
harmony 鸿蒙Media Library Kit (Media File Management Service)
harmony 鸿蒙Playing Moving Photos with MovingPhotoView
harmony 鸿蒙Accessing and Managing Moving Photos
harmony 鸿蒙Observing Media Assets
harmony 鸿蒙Introduction to Media Library Kit
harmony 鸿蒙Managing Media Assets
- 所属分类: 后端技术
- 本文标签:
热门推荐
-
2、 - 优质文章
-
3、 gate.io
-
8、 golang
-
9、 openharmony
-
10、 Vue中input框自动聚焦