harmony 鸿蒙@ohos.file.photoAccessHelper (Album Management)

2023-10-30 浏览 (891)

@ohos.file.photoAccessHelper (Album Management)

The photoAccessHelper module provides APIs for album management, including creating an album and accessing and modifying media data in an album.

NOTE

The initial APIs of this module are supported since API version 10. Newly added APIs will be marked with a superscript to indicate their earliest API version.

Modules to Import

import photoAccessHelper from '@ohos.file.photoAccessHelper';

photoAccessHelper.getPhotoAccessHelper

getPhotoAccessHelper(context: Context): PhotoAccessHelper

Obtains a PhotoAccessHelper instance for accessing and modifying media files in the album.

Model restriction: This API can be used only in the stage model.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
contextContextYesContext of the ability instance.

Return value

TypeDescription
PhotoAccessHelperReturns the PhotoAccessHelper instance created.

Error codes

For details about the error codes, see Universal Error Codes.

IDError Message
401if parameter is invalid.

Example

// The phAccessHelper instance obtained is a global object. It is used by default in subsequent operations. If the code snippet is not added, an error will be reported indicating that phAccessHelper is not defined.
const context = getContext(this);
let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);

PhotoAccessHelper

getAssets

getAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<PhotoAsset>>): void;

Obtains image and video assets. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.READ_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
optionsFetchOptionsYesOptions for fetching the image and video assets.
callbackAsyncCallback<FetchResult<PhotoAsset>>YesCallback invoked to return the image and video assets obtained.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('getAssets');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };

  phAccessHelper.getAssets(fetchOptions, async (err, fetchResult) => {
    if (fetchResult != undefined) {
      console.info('fetchResult success');
      let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
      if (photoAsset != undefined) {
        console.info('photoAsset.displayName : ' + photoAsset.displayName);
      }
    } else {
      console.error('fetchResult fail' + err);
    }
  });
}

getAssets

getAssets(options: FetchOptions): Promise<FetchResult<PhotoAsset>>;

Obtains image and video assets. This API uses a promise to return the result.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.READ_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
optionsFetchOptionsYesOptions for fetching the image and video assets.

Return value

TypeDescription
Promise<FetchResult<PhotoAsset>>Promise used to return the image and video assets obtained.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('getAssets');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  try {
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOptions);
    if (fetchResult != undefined) {
      console.info('fetchResult success');
      let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
      if (photoAsset != undefined) {
        console.info('photoAsset.displayName :' + photoAsset.displayName);
      }
    }
  } catch (err) {
    console.error('getAssets failed, message = ', err);
  }
}

createAsset

createAsset(displayName: string, callback: AsyncCallback<PhotoAsset>): void;

Creates an image or video asset with the specified file name. This API uses an asynchronous callback to return the result.

System API: This is a system API.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
displayNamestringYesFile name of the image or video to create.
callbackAsyncCallback<PhotoAsset>YesCallback invoked to return the image or video created.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000001Invalid display name.
14000011System inner fail.

Example

async function example() {
  console.info('createAssetDemo');
  let testFileName: string = 'testFile' + Date.now() + '.jpg';
  phAccessHelper.createAsset(testFileName, (err, photoAsset) => {
    if (photoAsset != undefined) {
      console.info('createAsset file displayName' + photoAsset.displayName);
      console.info('createAsset successfully');
    } else {
      console.error('createAsset failed, message = ', err);
    }
  });
}

createAsset

createAsset(displayName: string): Promise<PhotoAsset>;

Creates an image or video asset with the specified file name. This API uses a promise to return the result.

System API: This is a system API.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
displayNamestringYesFile name of the image or video to create.

Return value

TypeDescription
Promise<PhotoAsset>Promise used to return the created image and video asset.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000001Invalid display name.
14000011System inner fail.

Example

async function example() {
  console.info('createAssetDemo');
  try {
    let testFileName: string = 'testFile' + Date.now() + '.jpg';
    let photoAsset: photoAccessHelper.PhotoAsset = await phAccessHelper.createAsset(testFileName);
    console.info('createAsset file displayName' + photoAsset.displayName);
    console.info('createAsset successfully');
  } catch (err) {
    console.error('createAsset failed, message = ', err);
  }
}

createAsset

createAsset(displayName: string, options: PhotoCreateOptions, callback: AsyncCallback<PhotoAsset>): void;

Creates an image or video asset with the specified file name and options. This API uses an asynchronous callback to return the result.

System API: This is a system API.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
displayNamestringYesFile name of the image or video to create.
optionsPhotoCreateOptionsYesOptions for creating an image or video asset.
callbackAsyncCallback<PhotoAsset>YesCallback invoked to return the image or video created.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000001Invalid display name.
14000011System inner fail.

Example

async function example() {
  console.info('createAssetDemo');
  let testFileName: string = 'testFile' + Date.now() + '.jpg';
  let createOption: photoAccessHelper.PhotoCreateOptions = {
    subtype: photoAccessHelper.PhotoSubtype.DEFAULT
  }
  phAccessHelper.createAsset(testFileName, createOption, (err, photoAsset) => {
    if (photoAsset != undefined) {
      console.info('createAsset file displayName' + photoAsset.displayName);
      console.info('createAsset successfully');
    } else {
      console.error('createAsset failed, message = ', err);
    }
  });
}

createAsset

createAsset(displayName: string, options: PhotoCreateOptions): Promise<PhotoAsset>;

Creates an image or video asset with the specified file name and options. This API uses a promise to return the result.

System API: This is a system API.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
displayNamestringYesFile name of the image or video to create.
optionsPhotoCreateOptionsYesOptions for creating an image or video asset.

Return value

TypeDescription
Promise<PhotoAsset>Promise used to return the created image and video asset.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000001Invalid display name.
14000011System inner fail.

Example

async function example() {
  console.info('createAssetDemo');
  try {
    let testFileName:string = 'testFile' + Date.now() + '.jpg';
    let createOption: photoAccessHelper.PhotoCreateOptions = {
      subtype: photoAccessHelper.PhotoSubtype.DEFAULT
    }
    let photoAsset: photoAccessHelper.PhotoAsset = await phAccessHelper.createAsset(testFileName, createOption);
    console.info('createAsset file displayName' + photoAsset.displayName);
    console.info('createAsset successfully');
  } catch (err) {
    console.error('createAsset failed, message = ', err);
  }
}

createAsset

createAsset(photoType: PhotoType, extension: string, options: CreateOptions, callback: AsyncCallback<string>): void;

Creates an image or video asset with the specified file type, file name extension, and options. This API uses an asynchronous callback to return the result.

If the application does not have the ohos.permission.WRITE_IMAGEVIDEO permission, you can use a security component to create a media asset. For details, see Creating a Media Asset Using a Security Component.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
photoTypePhotoTypeYesType of the file to create, which can be IMAGE or VIDEO.
extensionstringYesFile name extension, for example, jpg.
optionsCreateOptionsYesOptions for creating the image or video asset, for example, {title: 'testPhoto'}.
callbackAsyncCallback<string>YesCallback invoked to return the URI of the created image or video.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

async function example() {
  console.info('createAssetDemo');
  let photoType: photoAccessHelper.PhotoType = photoAccessHelper.PhotoType.IMAGE;
  let extension:string = 'jpg';
  let options: photoAccessHelper.CreateOptions = {
    title: 'testPhoto'
  }
  phAccessHelper.createAsset(photoType, extension, options, (err, uri) => {
    if (uri != undefined) {
      console.info('createAsset uri' + uri);
      console.info('createAsset successfully');
    } else {
      console.error('createAsset failed, message = ', err);
    }
  });
}

createAsset

createAsset(photoType: PhotoType, extension: string, callback: AsyncCallback<string>): void;

Creates an image or video asset with the specified file type and file name extension. This API uses an asynchronous callback to return the result.

If the application does not have the ohos.permission.WRITE_IMAGEVIDEO permission, you can use a security component to create a media asset. For details, see Creating a Media Asset Using a Security Component.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
photoTypePhotoTypeYesType of the file to create, which can be IMAGE or VIDEO.
extensionstringYesFile name extension, for example, jpg.
callbackAsyncCallback<string>YesCallback invoked to return the URI of the created image or video.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

async function example() {
  console.info('createAssetDemo');
  let photoType: photoAccessHelper.PhotoType = photoAccessHelper.PhotoType.IMAGE;
  let extension: string = 'jpg';
  phAccessHelper.createAsset(photoType, extension, (err, uri) => {
    if (uri != undefined) {
      console.info('createAsset uri' + uri);
      console.info('createAsset successfully');
    } else {
      console.error('createAsset failed, message = ', err);
    }
  });
}

createAsset

createAsset(photoType: PhotoType, extension: string, options?: CreateOptions): Promise<string>;

Creates an image or video asset with the specified file type, file name extension, and options. This API uses a promise to return the result.

If the application does not have the ohos.permission.WRITE_IMAGEVIDEO permission, you can use a security component to create a media asset. For details, see Creating a Media Asset Using a Security Component.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
photoTypePhotoTypeYesType of the file to create, which can be IMAGE or VIDEO.
extensionstringYesFile name extension, for example, jpg.
optionsCreateOptionsNoOptions for creating the image or video asset, for example, {title: 'testPhoto'}.

Return value

TypeDescription
Promise<string>Promise used to return the URI of the created image or video asset.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

async function example() {
  console.info('createAssetDemo');
  try {
    let photoType: photoAccessHelper.PhotoType = photoAccessHelper.PhotoType.IMAGE;
    let extension: string = 'jpg';
    let options: photoAccessHelper.CreateOptions = {
      title: 'testPhoto'
    }
    let uri: string = await phAccessHelper.createAsset(photoType, extension, options);
    console.info('createAsset uri' + uri);
    console.info('createAsset successfully');
  } catch (err) {
    console.error('createAsset failed, message = ', err);
  }
}

createAlbum

createAlbum(name: string, callback: AsyncCallback<Album>): void;

Creates an album. This API uses an asynchronous callback to return the result.

The album name must meet the following requirements:

  • The album name is a string of 1 to 255 characters.
  • The album name cannot contain any of the following characters:
    .. \ / : * ? " ' ` < >|{ } [ ]
  • The album name is case-insensitive.
  • Duplicate album names are not allowed.

System API: This is a system API.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
namestringYesName of the album to create.
callbackAsyncCallback<Album>YesCallback invoked to return the created album instance.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900015File exists.
13900020Invalid argument.
14000011System inner fail.

Example

async function example() {
  console.info('createAlbumDemo');
  let albumName: string = 'newAlbumName' + new Date().getTime();
  phAccessHelper.createAlbum(albumName, (err, album) => {
    if (err) {
      console.error('createAlbumCallback failed with err: ' + err);
      return;
    }
    console.info('createAlbumCallback successfully, album: ' + album.albumName + ' album uri: ' + album.albumUri);
  });
}

createAlbum

createAlbum(name: string): Promise<Album>;

Creates an album. This API uses a promise to return the result.

The album name must meet the following requirements:

  • The album name is a string of 1 to 255 characters.
  • The album name cannot contain any of the following characters:
    .. \ / : * ? " ' ` < >|{ } [ ]
  • The album name is case-insensitive.
  • Duplicate album names are not allowed.

System API: This is a system API.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
namestringYesName of the album to create.

Return value

TypeDescription
Promise<Album>Promise used to return the created album instance.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900015File exists.
13900020Invalid argument.
14000011System inner fail.

Example

import { BusinessError } from '@ohos.base';

async function example() {
  console.info('createAlbumDemo');
  let albumName: string = 'newAlbumName' + new Date().getTime();
  phAccessHelper.createAlbum(albumName).then((album) => {
    console.info('createAlbumPromise successfully, album: ' + album.albumName + ' album uri: ' + album.albumUri);
  }).catch((err: BusinessError) => {
    console.error('createAlbumPromise failed with err: ' + err);
  });
}

deleteAlbums

deleteAlbums(albums: Array<Album>, callback: AsyncCallback<void>): void;

Deletes albums. This API uses an asynchronous callback to return the result.

Ensure that the albums to be deleted exist. Only user albums can be deleted.

System API: This is a system API.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
albumsArray<Album>YesAlbums to delete.
callbackAsyncCallback<void>YesCallback that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  // Delete the album named newAlbumName.
  console.info('deleteAlbumsDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  predicates.equalTo('album_name', 'newAlbumName');
  let fetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions);
  let album: photoAccessHelper.Album = await fetchResult.getFirstObject();
  phAccessHelper.deleteAlbums([album], (err) => {
    if (err) {
      console.error('deletePhotoAlbumsCallback failed with err: ' + err);
      return;
    }
    console.info('deletePhotoAlbumsCallback successfully');
  });
  fetchResult.close();
}

deleteAlbums

deleteAlbums(albums: Array<Album>): Promise<void>;

Deletes albums. This API uses a promise to return the result.

Ensure that the albums to be deleted exist. Only user albums can be deleted.

System API: This is a system API.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
albumsArray<Album>YesAlbums to delete.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

async function example() {
  // Delete the album named newAlbumName.
  console.info('deleteAlbumsDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  predicates.equalTo('album_name', 'newAlbumName');
  let fetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions);
  let album: photoAccessHelper.Album = await fetchResult.getFirstObject();
  phAccessHelper.deleteAlbums([album]).then(() => {
    console.info('deletePhotoAlbumsPromise successfully');
    }).catch((err: BusinessError) => {
      console.error('deletePhotoAlbumsPromise failed with err: ' + err);
  });
  fetchResult.close();
}

getAlbums

getAlbums(type: AlbumType, subtype: AlbumSubtype, options: FetchOptions, callback: AsyncCallback<FetchResult<Album>>): void;

Obtains albums based on the specified options and album type. This API uses an asynchronous callback to return the result.

Before the operation, ensure that the albums to obtain exist.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.READ_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
typeAlbumTypeYesType of the album to obtain.
subtypeAlbumSubtypeYesSubtype of the album.
optionsFetchOptionsYesOptions for fetching the albums.
callbackAsyncCallback<FetchResult<Album>>YesCallback invoked to return the result.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  // Obtain the album named newAlbumName.
  console.info('getAlbumsDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  predicates.equalTo('album_name', 'newAlbumName');
  let fetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions, async (err, fetchResult) => {
    if (err) {
      console.error('getAlbumsCallback failed with err: ' + err);
      return;
    }
    if (fetchResult == undefined) {
      console.error('getAlbumsCallback fetchResult is undefined');
      return;
    }
    let album = await fetchResult.getFirstObject();
    console.info('getAlbumsCallback successfully, albumName: ' + album.albumName);
    fetchResult.close();
  });
}

getAlbums

getAlbums(type: AlbumType, subtype: AlbumSubtype, callback: AsyncCallback<FetchResult<Album>>): void;

Obtains albums by type. This API uses an asynchronous callback to return the result.

Before the operation, ensure that the albums to obtain exist.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.READ_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
typeAlbumTypeYesType of the album to obtain.
subtypeAlbumSubtypeYesSubtype of the album.
callbackAsyncCallback<FetchResult<Album>>YesCallback invoked to return the result.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

async function example() {
  // Obtain the system album VIDEO, which is preset by default.
  console.info('getAlbumsDemo');
  phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.VIDEO, async (err, fetchResult) => {
    if (err) {
      console.error('getAlbumsCallback failed with err: ' + err);
      return;
    }
    if (fetchResult == undefined) {
      console.error('getAlbumsCallback fetchResult is undefined');
      return;
    }
    let album: photoAccessHelper.Album = await fetchResult.getFirstObject();
    console.info('getAlbumsCallback successfully, albumUri: ' + album.albumUri);
    fetchResult.close();
  });
}

getAlbums

getAlbums(type: AlbumType, subtype: AlbumSubtype, options?: FetchOptions): Promise<FetchResult<Album>>;

Obtains albums based on the specified options and album type. This API uses a promise to return the result.

Before the operation, ensure that the albums to obtain exist.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Required permissions: ohos.permission.READ_IMAGEVIDEO

Parameters

NameTypeMandatoryDescription
typeAlbumTypeYesType of the album to obtain.
subtypeAlbumSubtypeYesSubtype of the album.
optionsFetchOptionsNoOptions for fetching the albums. If this parameter is not specified, the albums are obtained based on the album type by default.

Return value

TypeDescription
Promise<FetchResult<Album>>Promise used to return the result.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

async function example() {
  // Obtain the album named newAlbumName.
  console.info('getAlbumsDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  predicates.equalTo('album_name', 'newAlbumName');
  let fetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, fetchOptions).then( async (fetchResult) => {
    if (fetchResult == undefined) {
      console.error('getAlbumsPromise fetchResult is undefined');
      return;
    }
    let album: photoAccessHelper.Album = await fetchResult.getFirstObject();
    console.info('getAlbumsPromise successfully, albumName: ' + album.albumName);
    fetchResult.close();
  }).catch((err: BusinessError) => {
    console.error('getAlbumsPromise failed with err: ' + err);
  });
}

deleteAssets

deleteAssets(uriList: Array<string>, callback: AsyncCallback<void>): void;

Deletes media files. This API uses an asynchronous callback to return the result. The deleted files are moved to the trash.

System API: This is a system API.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
uriListArray<string>YesURIs of the media files to delete.
callbackAsyncCallback<void>YesCallback that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000002Invalid uri.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('deleteAssetDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  try {
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOptions);
    let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    if (asset == undefined) {
      console.error('asset not exist');
      return;
    }
    phAccessHelper.deleteAssets([asset.uri], (err) => {
      if (err == undefined) {
        console.info('deleteAssets successfully');
      } else {
        console.error('deleteAssets failed with error: ' + err);
      }
    });
  } catch (err) {
    console.info('fetch failed, message =', err);
  }
}

deleteAssets

deleteAssets(uriList: Array<string>): Promise<void>;

Deletes media files. This API uses a promise to return the result. The deleted files are moved to the trash.

System API: This is a system API.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
uriListArray<string>YesURIs of the media files to delete.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000002Invalid uri.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('deleteDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  try {
    const fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOptions);
    let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    if (asset == undefined) {
      console.error('asset not exist');
      return;
    }
    await phAccessHelper.deleteAssets([asset.uri]);
    console.info('deleteAssets successfully');
  } catch (err) {
    console.error('deleteAssets failed with error: ' + err);
  }
}

registerChange

registerChange(uri: string, forChildUris: boolean, callback: Callback<ChangeData>) : void

Registers listening for the specified URI. This API uses a callback to return the result.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
uristringYesURI of the photo asset, URI of the album, or DefaultChangeUri.
forChildUrisbooleanYesWhether to perform fuzzy listening.
If uri is the URI of an album, the value true means to listen for the changes of the files in the album; the value false means to listen for the changes of the album only.
If uri is the URI of a photoAsset, there is no difference between true and false for forChildUris.
If uri is DefaultChangeUri, forChildUris must be set to true. If forChildUris is false, the URI cannot be found and no message can be received.
callbackCallback<ChangeData>YesCallback invoked to return the ChangeData.
NOTE
Multiple callback listeners can be registered for a URI. You can use unRegisterChange to unregister all listeners for the URI or a specified callback listener.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('registerChangeDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOptions);
  let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
  if (photoAsset != undefined) {
    console.info('photoAsset.displayName : ' + photoAsset.displayName);
  }
  let onCallback1 = (changeData: photoAccessHelper.ChangeData) => {
      console.info('onCallback1 success, changData: ' + JSON.stringify(changeData));
    //file had changed, do something
  }
  let onCallback2 = (changeData: photoAccessHelper.ChangeData) => {
      console.info('onCallback2 success, changData: ' + JSON.stringify(changeData));
    //file had changed, do something
  }
  // Register onCallback1.
  phAccessHelper.registerChange(photoAsset.uri, false, onCallback1);
  // Register onCallback2.
  phAccessHelper.registerChange(photoAsset.uri, false, onCallback2);

  photoAsset.setFavorite(true, (err) => {
    if (err == undefined) {
      console.info('setFavorite successfully');
    } else {
      console.error('setFavorite failed with error:' + err);
    }
  });
}

unRegisterChange

unRegisterChange(uri: string, callback?: Callback<ChangeData>): void

Unregisters listening for the specified URI. Multiple callbacks can be registered for a URI for listening. You can use this API to unregister the listening of the specified callbacks or all callbacks.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
uristringYesURI of the photo asset, URI of the album, or DefaultChangeUri.
callbackCallback<ChangeData>NoCallback to unregister. If this parameter is not specified, all the callbacks for listening for the URI will be canceled.
NOTE: The specified callback unregistered will not be invoked when the data changes.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('offDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOptions);
  let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
  if (photoAsset != undefined) {
    console.info('photoAsset.displayName : ' + photoAsset.displayName);
  }
  let onCallback1 = (changeData: photoAccessHelper.ChangeData) => {
    console.info('onCallback1 on');
  }
  let onCallback2 = (changeData: photoAccessHelper.ChangeData) => {
    console.info('onCallback2 on');
  }
  // Register onCallback1.
  phAccessHelper.registerChange(photoAsset.uri, false, onCallback1);
  // Register onCallback2.
  phAccessHelper.registerChange(photoAsset.uri, false, onCallback2);
  // Unregister the listening of onCallback1.
  phAccessHelper.unRegisterChange(photoAsset.uri, onCallback1);
  photoAsset.setFavorite(true, (err) => {
    if (err == undefined) {
      console.info('setFavorite successfully');
    } else {
      console.error('setFavorite failed with error:' + err);
    }
  });
}

createDeleteRequest

createDeleteRequest(uriList: Array<string>, callback: AsyncCallback<void>): void;

Creates a dialog box for deleting media files. This API uses an asynchronous callback to return the result. The deleted media files are moved to the trash.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
uriListArray<string>YesURIs of the media files to delete. A maximum of 300 media files can be deleted.
callbackAsyncCallback<void>YesCallback that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('createDeleteRequestDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  try {
    const fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOptions);
    let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    if (asset == undefined) {
      console.error('asset not exist');
      return;
    }
    phAccessHelper.createDeleteRequest([asset.uri], (err) => {
      if (err == undefined) {
        console.info('createDeleteRequest successfully');
      } else {
        console.error('createDeleteRequest failed with error: ' + err);
      }
    });
  } catch (err) {
    console.info('fetch failed, message =', err);
  }
}

createDeleteRequest

createDeleteRequest(uriList: Array<string>): Promise<void>;

Creates a dialog box for deleting media files. This API uses a promise to return the result. The deleted media files are moved to the trash.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
uriListArray<string>YesURIs of the media files to delete. A maximum of 300 media files can be deleted.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('createDeleteRequestDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  try {
    const fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOptions);
    let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    if (asset == undefined) {
      console.error('asset not exist');
      return;
    }
    await phAccessHelper.createDeleteRequest([asset.uri]);
    console.info('createDeleteRequest successfully');
  } catch (err) {
    console.error('createDeleteRequest failed with error: ' + err);
  }
}

getPhotoIndex

getPhotoIndex(photoUri: string, albumUri: string, options: FetchOptions, callback: AsyncCallback<number>): void

Obtains the index of an image or video in an album. This API uses an asynchronous callback to return the result.

System API: This is a system API.

Required permissions: ohos.permission.READ_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
photoUristringYesURI of the media asset whose index is to be obtained.
albumUristringYesAlbum URI, which can be an empty string. If it is an empty string, all the media assets in the Gallery are obtained by default.
optionsFetchOptionsYesFetch options. Only one search condition or sorting mode must be set in predicates. If no value is set or multiple search conditions or sorting modes are set, the API cannot be called successfully.

Return value

TypeDescription
AsyncCallback<number>Promise used to return the index obtained.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  try {
    console.info('getPhotoIndexDemo');
    let predicatesForGetAsset: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOp: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicatesForGetAsset
    };
    // Obtain the uri of the album
    let albumFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE, fetchOp);
    let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject();
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    predicates.orderByAsc(photoAccessHelper.PhotoKeys.DATE_MODIFIED);
    let fetchOptions: photoAccessHelper.FetchOptions = {
      fetchColumns: [photoAccessHelper.PhotoKeys.DATE_MODIFIED],
      predicates: predicates
    };
    let photoFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await album.getAssets(fetchOptions);
    let expectIndex = 1;
    // Obtain the uri of the second file
    let photoAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getObjectByPosition(expectIndex);

    phAccessHelper.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions, (err, index) => {
      if (err == undefined) {
        console.info(`getPhotoIndex successfully and index is : ${index}`);
      } else {
        console.info(`getPhotoIndex failed;`);
      }
    });
  } catch (error) {
    console.info(`getPhotoIndex failed; error: ${error}`);
  }
}

getPhotoIndex

getPhotoIndex(photoUri: string, albumUri: string, options: FetchOptions): Promise<number>

Obtains the index of an image or video in an album. This API uses a promise to return the result.

System API: This is a system API.

Required permissions: ohos.permission.READ_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
photoUristringYesURI of the media asset whose index is to be obtained.
albumUristringYesAlbum URI, which can be an empty string. If it is an empty string, all the media assets in the Gallery are obtained by default.
optionsFetchOptionsYesFetch options. Only one search condition or sorting mode must be set in predicates. If no value is set or multiple search conditions or sorting modes are set, the API cannot be called successfully.

Return value

TypeDescription
Promise<number>Promise used to return the index obtained.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

async function example() {
  try {
    console.info('getPhotoIndexDemo');
    let predicatesForGetAsset: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOp: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicatesForGetAsset
    };
    // Obtain the uri of the album
    let albumFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.FAVORITE, fetchOp);
    let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject();
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    predicates.orderByAsc(photoAccessHelper.PhotoKeys.DATE_MODIFIED);
    let fetchOptions: photoAccessHelper.FetchOptions = {
      fetchColumns: [photoAccessHelper.PhotoKeys.DATE_MODIFIED],
      predicates: predicates
    };
    let photoFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await album.getAssets(fetchOptions);
    let expectIndex = 1;
    // Obtain the uri of the second file
    let photoAsset: photoAccessHelper.PhotoAsset = await photoFetchResult.getObjectByPosition(expectIndex);
    phAccessHelper.getPhotoIndex(photoAsset.uri, album.albumUri, fetchOptions).then((index) => {
      console.info(`getPhotoIndex successfully and index is : ${index}`);
    }).catch((err: BusinessError) => {
      console.info(`getPhotoIndex failed; error: ${err}`);
    });
  } catch (error) {
    console.info(`getPhotoIndex failed; error: ${error}`);
  }
}

release

release(callback: AsyncCallback<void>): void

Releases the PhotoAccessHelper instance. This API uses an asynchronous callback to return the result. Call this API when the APIs of the PhotoAccessHelper instance are no longer used.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback used to return the result.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

async function example() {
  console.info('releaseDemo');
  phAccessHelper.release((err) => {
    if (err != undefined) {
      console.error('release failed. message = ', err);
    } else {
      console.info('release ok.');
    }
  });
}

release

release(): Promise<void>

Releases the PhotoAccessHelper instance. This API uses a promise to return the result. Call this API when the APIs of the PhotoAccessHelper instance are no longer used.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

async function example() {
  console.info('releaseDemo');
  try {
    await phAccessHelper.release();
    console.info('release ok.');
  } catch (err) {
    console.error('release failed. message = ', err);
  }
}

PhotoAsset

Provides APIs for encapsulating file asset attributes.

Attributes

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeReadableWritableDescription
uristringYesNoMedia asset URI, for example, file://media/Photo/1/IMG_datetime_0001/displayName.jpg. For details, see Media File URI.
photoTypePhotoTypeYesNoType of the file.
displayNamestringYesNoFile name, including the file name extension, to display.

get

get(member: string): MemberType;

Obtains a PhotoAsset member parameter.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
memberstringYesName of the member parameter to obtain. Except uri, photoType, and displayName, you need to pass in PhotoKeys in fetchColumns in get(). For example, to obtain the title attribute, set fetchColumns: ['title'].

Return value

TypeDescription
MemberTypeReturns the PhotoAsset member parameter obtained.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000014Member is not a valid PhotoKey.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('photoAssetGetDemo');
  try {
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: ['title'],
      predicates: predicates
    };
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
    let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    let title: photoAccessHelper.PhotoKeys = photoAccessHelper.PhotoKeys.TITLE;
    let photoAssetTitle: photoAccessHelper.MemberType = photoAsset.get(title.toString());
    console.info('photoAsset Get photoAssetTitle = ', photoAssetTitle);
  } catch (err) {
    console.error('release failed. message = ', err);
  }
}

set

set(member: string, value: string): void;

Sets a PhotoAsset member parameter.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
memberstringYesName of the member parameter to set. For example, PhotoKeys.TITLE.
valuestringYesMember parameter to set. Only the value of PhotoKeys.TITLE can be modified.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000014Member is not a valid PhotoKey.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('photoAssetSetDemo');
  try {
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: ['title'],
      predicates: predicates
    };
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
    let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    let title: string = photoAccessHelper.PhotoKeys.TITLE.toString();
    photoAsset.set(title, 'newTitle');
  } catch (err) {
    console.error('release failed. message = ', err);
  }
}

commitModify

commitModify(callback: AsyncCallback<void>): void

Commits the modification on the file metadata to the database. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if values to commit is invalid.
13900012Permission denied.
13900020Invalid argument.
14000001Invalid display name.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('commitModifyDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: ['title'],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
  let title: string = photoAccessHelper.PhotoKeys.TITLE.toString();
  let photoAssetTitle: photoAccessHelper.MemberType = photoAsset.get(title);
  console.info('photoAsset get photoAssetTitle = ', photoAssetTitle);
  photoAsset.set(title, 'newTitle2');
  photoAsset.commitModify((err) => {
    if (err == undefined) {
      let newPhotoAssetTitle: photoAccessHelper.MemberType = photoAsset.get(title);
      console.info('photoAsset get newPhotoAssetTitle = ', newPhotoAssetTitle);
    } else {
      console.error('commitModify failed, message =', err);
    }
  });
}

commitModify

commitModify(): Promise<void>

Commits the modification on the file metadata to the database. This API uses a promise to return the result.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if values to commit is invalid.
13900012Permission denied.
13900020Invalid argument.
14000001Invalid display name.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('commitModifyDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: ['title'],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
  let title: string = photoAccessHelper.PhotoKeys.TITLE.toString();
  let photoAssetTitle: photoAccessHelper.MemberType = photoAsset.get(title);
  console.info('photoAsset get photoAssetTitle = ', photoAssetTitle);
  photoAsset.set(title, 'newTitle3');
  try {
    await photoAsset.commitModify();
    let newPhotoAssetTitle: photoAccessHelper.MemberType = photoAsset.get(title);
    console.info('photoAsset get newPhotoAssetTitle = ', newPhotoAssetTitle);
  } catch (err) {
    console.error('release failed. message = ', err);
  }
}

open

open(mode: string, callback: AsyncCallback<number>): void

Opens this file asset. This API uses an asynchronous callback to return the result.

NOTE
The write operations are mutually exclusive. After a write operation is complete, you must call close to close the file.

System API: This is a system API.

Required permissions: ohos.permission.READ_IMAGEVIDEO or ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
modestringYesFile open mode, which can be r (read-only), w (write-only), or rw (read-write).
callbackAsyncCallback<number>YesCallback invoked to return the file descriptor of the file opened.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

async function example() {
  console.info('openDemo');
   let testFileName: string = 'testFile' + Date.now() + '.jpg';
  const photoAsset: photoAccessHelper.PhotoAsset = await phAccessHelper.createAsset(testFileName);
  photoAsset.open('rw', (err, fd) => {
    if (fd != undefined) {
      console.info('File fd' + fd);
      photoAsset.close(fd);
    } else {
      console.error('File err' + err);
    }
  });
}

open

open(mode: string): Promise<number>

Opens this file asset. This API uses a promise to return the result.

NOTE
The write operations are mutually exclusive. After a write operation is complete, you must call close to close the file.

System API: This is a system API.

Required permissions: ohos.permission.READ_IMAGEVIDEO or ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
modestringYesFile open mode, which can be r (read-only), w (write-only), or rw (read-write).

Return value

TypeDescription
Promise<number>Promise used to return the file descriptor of the file opened.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

async function example() {
  console.info('openDemo');
  try {
    let testFileName: string = 'testFile' + Date.now() + '.jpg';
    const photoAsset: photoAccessHelper.PhotoAsset = await phAccessHelper.createAsset(testFileName);
    let fd: number = await photoAsset.open('rw');
    if (fd != undefined) {
      console.info('File fd' + fd);
      photoAsset.close(fd);
    } else {
      console.error(' open File fail');
    }
  } catch (err) {
    console.error('open Demo err' + err);
  }
}

getReadOnlyFd

getReadOnlyFd(callback: AsyncCallback<number>): void

Opens this file in read-only mode. This API uses an asynchronous callback to return the result.

NOTE
After the read operation is complete, call close to close the file.

Required permissions: ohos.permission.READ_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<number>YesCallback invoked to return the file descriptor of the file opened.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

async function example() {
  console.info('getReadOnlyFdDemo');
   let testFileName: string = 'testFile' + Date.now() + '.jpg';
  const photoAsset: photoAccessHelper.PhotoAsset = await phAccessHelper.createAsset(testFileName);
  photoAsset.getReadOnlyFd((err, fd) => {
    if (fd != undefined) {
      console.info('File fd' + fd);
      photoAsset.close(fd);
    } else {
      console.error('File err' + err);
    }
  });
}

getReadOnlyFd

getReadOnlyFd(): Promise<number>

Opens this file in read-only mode. This API uses a promise to return the result.

NOTE
After the read operation is complete, call close to close the file.

Required permissions: ohos.permission.READ_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Return value

TypeDescription
Promise<number>Promise used to return the file descriptor of the file opened.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

async function example() {
  console.info('getReadOnlyFdDemo');
  try {
    let testFileName: string = 'testFile' + Date.now() + '.jpg';
    const photoAsset: photoAccessHelper.PhotoAsset = await phAccessHelper.createAsset(testFileName);
    let fd: number = await photoAsset.getReadOnlyFd();
    if (fd != undefined) {
      console.info('File fd' + fd);
      photoAsset.close(fd);
    } else {
      console.error(' open File fail');
    }
  } catch (err) {
    console.error('open Demo err' + err);
  }
}

close

close(fd: number, callback: AsyncCallback<void>): void

Closes a file. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
fdnumberYesFile descriptor of the file to close.
callbackAsyncCallback<void>YesCallback that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('closeDemo');
  try {
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
    const photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    let fd: number = await photoAsset.open('rw');
    console.info('file fd', fd);
    photoAsset.close(fd, (err) => {
      if (err == undefined) {
        console.info('asset close succeed.');
      } else {
        console.error('close failed, message = ' + err);
      }
    });
  } catch (err) {
    console.error('close failed, message = ' + err);
  }
}

close

close(fd: number): Promise<void>

Closes a file. This API uses a promise to return the result.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
fdnumberYesFile descriptor of the file to close.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('closeDemo');
  try {
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
    const asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    let fd = await asset.open('rw');
    console.info('file fd', fd);
    await asset.close(fd);
    console.info('asset close succeed.');
  } catch (err) {
    console.error('close failed, message = ' + err);
  }
}

getThumbnail

getThumbnail(callback: AsyncCallback<image.PixelMap>): void

Obtains the thumbnail of this file. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.READ_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<image.PixelMap>YesCallback invoked to return the PixelMap of the thumbnail.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('getThumbnailDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  const asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
  console.info('asset displayName = ', asset.displayName);
  asset.getThumbnail((err, pixelMap) => {
    if (err == undefined) {
      console.info('getThumbnail successful ' + pixelMap);
    } else {
      console.error('getThumbnail fail', err);
    }
  });
}

getThumbnail

getThumbnail(size: image.Size, callback: AsyncCallback<image.PixelMap>): void

Obtains the file thumbnail of the given size. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.READ_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
sizeimage.SizeYesSize of the thumbnail.
callbackAsyncCallback<image.PixelMap>YesCallback invoked to return the PixelMap of the thumbnail.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import image from '@ohos.multimedia.image'

async function example() {
  console.info('getThumbnailDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let size: image.Size = { width: 720, height: 720 };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  const asset = await fetchResult.getFirstObject();
  console.info('asset displayName = ', asset.displayName);
  asset.getThumbnail(size, (err, pixelMap) => {
    if (err == undefined) {
      console.info('getThumbnail successful ' + pixelMap);
    } else {
      console.error('getThumbnail fail', err);
    }
  });
}

getThumbnail

getThumbnail(size?: image.Size): Promise<image.PixelMap>

Obtains the file thumbnail of the given size. This API uses a promise to return the result.

Required permissions: ohos.permission.READ_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
sizeimage.SizeNoSize of the thumbnail.

Return value

TypeDescription
Promise<image.PixelMap>Promise used to return the PixelMap of the thumbnail.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import image from '@ohos.multimedia.image'
import { BusinessError } from '@ohos.base';

async function example() {
  console.info('getThumbnailDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let size: image.Size = { width: 720, height: 720 };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  const asset = await fetchResult.getFirstObject();
  console.info('asset displayName = ', asset.displayName);
  asset.getThumbnail(size).then((pixelMap) => {
    console.info('getThumbnail successful ' + pixelMap);
  }).catch((err: BusinessError) => {
    console.error('getThumbnail fail' + err);
  });
}

setFavorite

setFavorite(favoriteState: boolean, callback: AsyncCallback<void>): void

Favorites or unfavorites this file. This API uses an asynchronous callback to return the result.

System API: This is a system API.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
favoriteStatebooleanYesOperation to perform. The value true means to favorite the file asset, and false means the opposite.
callbackAsyncCallback<void>YesCallback that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('setFavoriteDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  const asset = await fetchResult.getFirstObject();
  asset.setFavorite(true, (err) => {
    if (err == undefined) {
      console.info('favorite successfully');
    } else {
      console.error('favorite failed with error:' + err);
    }
  });
}

setFavorite

setFavorite(favoriteState: boolean): Promise<void>

Favorites or unfavorites this file asset. This API uses a promise to return the result.

System API: This is a system API.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
favoriteStatebooleanYesOperation to perform. The value true means to favorite the file asset, and false means the opposite.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

async function example() {
  console.info('setFavoriteDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  const asset = await fetchResult.getFirstObject();
  asset.setFavorite(true).then(() => {
    console.info('setFavorite successfully');
  }).catch((err: BusinessError) => {
    console.error('setFavorite failed with error:' + err);
  });
}

setHidden

setHidden(hiddenState: boolean, callback: AsyncCallback<void>): void

Sets this file to hidden state. This API uses an asynchronous callback to return the result.

Private files are stored in the private album. After obtaining private files from the private album, users can set hiddenState to false to remove them from the private album.

System API: This is a system API.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
hiddenStatebooleanYesWhether to set a file to hidden state. The value true means to hide the file; the value false means the opposite.
callbackAsyncCallback<void>YesCallback that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('setHiddenDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  const asset = await fetchResult.getFirstObject();
  asset.setHidden(true, (err) => {
    if (err == undefined) {
      console.info('setHidden successfully');
    } else {
      console.error('setHidden failed with error:' + err);
    }
  });
}

setHidden

setHidden(hiddenState: boolean): Promise<void>

Sets this file asset to hidden state. This API uses a promise to return the result.

Private files are stored in the private album. After obtaining private files from the private album, users can set hiddenState to false to remove them from the private album.

System API: This is a system API.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
hiddenStatebooleanYesWhether to set a file to hidden state. The value true means to hide the file; the value false means the opposite.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

async function example() {
  // Restore a file from a hidden album. Before the operation, ensure that the file exists in the hidden album.
  console.info('setHiddenDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let albumList: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.HIDDEN);
  const album = await albumList.getFirstObject();
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await album.getAssets(fetchOption);
  const asset = await fetchResult.getFirstObject();
  asset.setHidden(false).then(() => {
    console.info('setHidden successfully');
  }).catch((err: BusinessError) => {
    console.error('setHidden failed with error:' + err);
  });
}

getExif10+

getExif(): Promise<string>

Obtains a JSON string consisting of the EXIF tags of this JPG image. This API uses a promise to return the result.

CAUTION
This API returns a JSON string consisting of EXIF tags. The complete EXIF information consists of all_exif and PhotoKeys.USER_COMMENT. These two fields must be passed in via fetchColumns.

System API: This is a system API.

Required permissions: ohos.permission.READ_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Return value

TypeDescription
Promise<string>Callback invoked to return the JSON string obtained.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Supported EXIF tags

For details about the EXIF tags, see image.PropertyKey.

Key ValueDescription
BitsPerSampleNumber of bits per pixel.
OrientationImage orientation.
ImageLengthImage length.
ImageWidthImage width.
GPSLatitudeGPS latitude of the image.
GPSLongitudeGPS longitude of the image.
GPSLatitudeRefLongitude reference, for example, W or E.
GPSLongitudeRefLatitude reference, for example, N or S.
DateTimeOriginalShooting time.
ExposureTimeExposure time.
SceneTypeShooting scene type.
ISOSpeedRatingsISO sensitivity or speed.
FNumberf-number.
DateTimeDate and time when the image was last modified.
GPSTimeStampGPS timestamp.
GPSDateStampGPS date stamp.
ImageDescriptionImage description.
MakeCamera vendor.
MakeNoteCamera vendor.
ModelModel.
PhotoModePhoto mode.
SensitivityTypeSensitivity type.
StandardOutputSensitivityStandard output sensitivity.
RecommendedExposureIndexRecommended exposure index.
ApertureValueAperture value.
MeteringModeMetering mode.
LightSourceLight source.
FlashFlash status.
FocalLengthFocal length.
UserCommentUser comment.
PixelXDimensionPixel X dimension.
PixelYDimensionPixel Y dimension.
WhiteBalanceWhite balance.
FocalLengthIn35mmFilmFocal length in 35 mm film.
ExposureBiasValueExposure compensation.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  try {
    console.info('getExifDemo');
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOptions: photoAccessHelper.FetchOptions = {
      fetchColumns: [ 'all_exif',  photoAccessHelper.PhotoKeys.USER_COMMENT],
      predicates: predicates
    };
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOptions);
    let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    let exifMessage = await photoAsset.getExif();
    let userCommentKey = 'UserComment';
    let userComment = JSON.stringify(JSON.parse(exifMessage), [userCommentKey]);
    fetchResult.close();
  } catch (err) {
    console.error('getExifDemoCallback failed with error: ' + err);
  }
}

getExif10+

getExif(callback: AsyncCallback<string>): void

Obtains a JSON string consisting of the EXIF tags of this JPG image. This API uses an asynchronous callback to return the result.

CAUTION
This API returns a JSON string consisting of EXIF tags. The complete EXIF information consists of all_exif and PhotoKeys.USER_COMMENT. These two fields must be passed in via fetchColumns.

System API: This is a system API.

Required permissions: ohos.permission.READ_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<string>YesCallback invoked to return the JSON string obtained.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Supported EXIF tags

For details about the EXIF tags, see image.PropertyKey.

Key ValueDescription
BitsPerSampleNumber of bits per pixel.
OrientationImage orientation.
ImageLengthImage length.
ImageWidthImage width.
GPSLatitudeGPS latitude of the image.
GPSLongitudeGPS longitude of the image.
GPSLatitudeRefLongitude reference, for example, W or E.
GPSLongitudeRefLatitude reference, for example, N or S.
DateTimeOriginalShooting time.
ExposureTimeExposure time.
SceneTypeShooting scene type.
ISOSpeedRatingsISO sensitivity or speed.
FNumberf-number.
DateTimeDate and time when the image was last modified.
GPSTimeStampGPS timestamp.
GPSDateStampGPS date stamp.
ImageDescriptionImage description.
MakeCamera vendor.
MakeNoteCamera vendor.
ModelModel.
PhotoModePhoto mode.
SensitivityTypeSensitivity type.
StandardOutputSensitivityStandard output sensitivity.
RecommendedExposureIndexRecommended exposure index.
ApertureValueAperture value.
MeteringModeMetering mode.
LightSourceLight source.
FlashFlash status.
FocalLengthFocal length.
UserCommentUser comment.
PixelXDimensionPixel X dimension.
PixelYDimensionPixel Y dimension.
WhiteBalanceWhite balance.
FocalLengthIn35mmFilmFocal length in 35 mm film.
ExposureBiasValueExposure compensation.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  try {
    console.info('getExifDemo');
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    predicates.isNotNull('all_exif')
    let fetchOptions: photoAccessHelper.FetchOptions = {
      fetchColumns: ['all_exif', photoAccessHelper.PhotoKeys.USER_COMMENT],
      predicates: predicates
    };
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOptions);
    let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    console.info('getExifDemo photoAsset displayName: ' + JSON.stringify(photoAsset.displayName));
    let userCommentKey = 'UserComment';
    photoAsset.getExif((err, exifMessage) => {
      if (exifMessage != undefined) {
        let userComment = JSON.stringify(JSON.parse(exifMessage), [userCommentKey]);
        console.info('getExifDemo userComment: ' + JSON.stringify(userComment));
      } else {
        console.error('getExif failed, message = ', err);
      }
    });
    fetchResult.close();
  } catch (err) {
    console.error('getExifDemoCallback failed with error: ' + err);
  }
}

setUserComment10+

setUserComment(userComment: string): Promise<void>

Sets user comment information of an image or video. This API uses a promise to return the result.

NOTE
This API can be used to modify the comment information of only images or videos.

System API: This is a system API.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
userCommentstringYesUser comment information to set, which cannot exceed 140 characters.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  try {
    console.info('setUserCommentDemo')
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOptions: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOptions);
    let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    let userComment = 'test_set_user_comment';
    await photoAsset.setUserComment(userComment);
  } catch (err) {
    console.error('setUserCommentDemoCallback failed with error: ' + err);
  }
}

setUserComment10+

setUserComment(userComment: string, callback: AsyncCallback<void>): void

Sets user comment information of an image or video. This API uses an asynchronous callback to return the result.

NOTE
This API can be used to modify the comment information of only images or videos.

System API: This is a system API.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
userCommentstringYesUser comment information to set, which cannot exceed 140 characters.
callbackAsyncCallback<void>YesCallback that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  try {
    console.info('setUserCommentDemo')
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOptions: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOptions);
    let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    let userComment = 'test_set_user_comment';
    photoAsset.setUserComment(userComment, (err) => {
      if (err === undefined) {
        console.info('setUserComment successfully');
      } else {
        console.error('setUserComment failed with error: ' + err);
      }
    });
  } catch (err) {
    console.error('setUserCommentDemoCallback failed with error: ' + err);
  }
}

PhotoViewPicker

Provides APIs for selecting images and videos. Before using the APIs of PhotoViewPicker, you need to create a PhotoViewPicker instance.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Example

let photoPicker = new photoAccessHelper.PhotoViewPicker();

select

select(option?: PhotoSelectOptions) : Promise<PhotoSelectResult>

Starts a photoPicker page for the user to select one or more images or videos. This API uses a promise to return the result. You can pass in PhotoSelectOptions to specify the media file type and the maximum number of files to select.

NOTE
The photoUris in the PhotoSelectResult object returned by this API can be used only by calling photoAccessHelper.getAssets() with temporary authorization. For details, see Using a Media File URI.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
optionPhotoSelectOptionsNoOptions for selecting files. If this parameter is not specified, images and videos are selected by default. A maximum of 50 files can be selected.

Return value

TypeDescription
Promise<PhotoSelectResult>Promise return information about the images or videos selected.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900042Unknown error.

Example

import { BusinessError } from '@ohos.base';
async function example01() {
  try {  
    let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
    PhotoSelectOptions.maxSelectNumber = 5;
    let photoPicker = new photoAccessHelper.PhotoViewPicker();
    photoPicker.select(PhotoSelectOptions).then((PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
      console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
    }).catch((err: BusinessError) => {
      console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err));
    });
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err));
  }
}

select

select(option: PhotoSelectOptions, callback: AsyncCallback<PhotoSelectResult>) : void

Starts a photoPicker page for the user to select one or more images or videos. This API uses an asynchronous callback to return the result. You can pass in PhotoSelectOptions to specify the media file type and the maximum number of files to select.

NOTE
The photoUris in the PhotoSelectResult object returned by this API can be used only by calling photoAccessHelper.getAssets() with temporary authorization. For details, see Using a Media File URI.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
optionPhotoSelectOptionsYesOptions for selecting images or videos.
callbackAsyncCallback<PhotoSelectResult>YesCallback invoked to return information about the images or videos selected.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900042Unknown error.

Example

import { BusinessError } from '@ohos.base';
async function example02() {
  try {
    let PhotoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
    PhotoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_TYPE;
    PhotoSelectOptions.maxSelectNumber = 5;
    let photoPicker = new photoAccessHelper.PhotoViewPicker();
    photoPicker.select(PhotoSelectOptions, (err: BusinessError, PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
      if (err) {
        console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err));
        return;
      }
      console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
    });
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err));
  }
}

select

select(callback: AsyncCallback<PhotoSelectResult>) : void

Starts a photoPicker page for the user to select one or more images or videos. This API uses an asynchronous callback to return the result.

NOTE
The photoUris in the PhotoSelectResult object returned by this API can be used only by calling photoAccessHelper.getAssets() with temporary authorization. For details, see Using a Media File URI.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<PhotoSelectResult>YesCallback invoked to return information about the images or videos selected.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900042Unknown error.

Example

import { BusinessError } from '@ohos.base';
async function example03() {
  try {
    let photoPicker = new photoAccessHelper.PhotoViewPicker();
    photoPicker.select((err: BusinessError, PhotoSelectResult: photoAccessHelper.PhotoSelectResult) => {
      if (err) {
        console.error('PhotoViewPicker.select failed with err: ' + JSON.stringify(err));
        return;
      }
      console.info('PhotoViewPicker.select successfully, PhotoSelectResult uri: ' + JSON.stringify(PhotoSelectResult));
    });
  } catch (error) {
    let err: BusinessError = error as BusinessError;
    console.error('PhotoViewPicker failed with err: ' + JSON.stringify(err));
  }
}

FetchResult

Provides APIs to manage the file retrieval result.

getCount

getCount(): number

Obtains the total number of files in the result set.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Return value

TypeDescription
numberReturns the total number of files obtained.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('getCountDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  const fetchCount = fetchResult.getCount();
  console.info('fetchCount = ', fetchCount);
}

isAfterLast

isAfterLast(): boolean

Checks whether the cursor is in the last row of the result set.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Return value

TypeDescription
booleanReturns true if the cursor is in the last row of the result set; returns false otherwise.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  const fetchCount = fetchResult.getCount();
  console.info('count:' + fetchCount);
  let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getLastObject();
  if (fetchResult.isAfterLast()) {
    console.info('photoAsset isAfterLast displayName = ', photoAsset.displayName);
  } else {
    console.info('photoAsset  not isAfterLast ');
  }
}

close

close(): void

Closes this FetchFileResult instance to invalidate it. After this instance is closed, the APIs in this instance cannot be invoked.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('fetchResultCloseDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  try {
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
    fetchResult.close();
    console.info('close succeed.');
  } catch (err) {
    console.error('close fail. message = ' + err);
  }
}

getFirstObject

getFirstObject(callback: AsyncCallback<T>): void

Obtains the first file asset in the result set. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<T>YesCallback invoked to return the first file asset obtained.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('getFirstObjectDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  fetchResult.getFirstObject((err, photoAsset) => {
    if (photoAsset != undefined) {
      console.info('photoAsset displayName: ', photoAsset.displayName);
    } else {
      console.error('photoAsset failed with err:' + err);
    }
  });
}

getFirstObject

getFirstObject(): Promise<T>

Obtains the first file asset in the result set. This API uses a promise to return the result.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Return value

TypeDescription
Promise<T>Promise used to return the first object in the result set.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('getFirstObjectDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
  console.info('photoAsset displayName: ', photoAsset.displayName);
}

getNextObject

getNextObject(callback: AsyncCallback<T>): void

Obtains the next file asset in the result set. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
callbackeAsyncCallback<T>YesCallback invoked to return the next file asset.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('getNextObjectDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  await fetchResult.getFirstObject();
  if (fetchResult.isAfterLast()) {
    fetchResult.getNextObject((err, photoAsset) => {
      if (photoAsset != undefined) {
        console.info('photoAsset displayName: ', photoAsset.displayName);
      } else {
        console.error('photoAsset failed with err: ' + err);
      }
    });
  }
}

getNextObject

getNextObject(): Promise<T>

Obtains the next file asset in the result set. This API uses a promise to return the result.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Return value

TypeDescription
Promise<T>Promise used to return the next object in the result set.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('getNextObjectDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  await fetchResult.getFirstObject();
  if (fetchResult.isAfterLast()) {
    let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getNextObject();
    console.info('photoAsset displayName: ', photoAsset.displayName);
  }
}

getLastObject

getLastObject(callback: AsyncCallback<T>): void

Obtains the last file asset in the result set. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<T>YesCallback invoked to return the last file asset obtained.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('getLastObjectDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  fetchResult.getLastObject((err, photoAsset) => {
    if (photoAsset != undefined) {
      console.info('photoAsset displayName: ', photoAsset.displayName);
    } else {
      console.error('photoAsset failed with err: ' + err);
    }
  });
}

getLastObject

getLastObject(): Promise<T>

Obtains the last file asset in the result set. This API uses a promise to return the result.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Return value

TypeDescription
Promise<T>Promise used to return the last object in the result set.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('getLastObjectDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getLastObject();
  console.info('photoAsset displayName: ', photoAsset.displayName);
}

getObjectByPosition

getObjectByPosition(index: number, callback: AsyncCallback<T>): void

Obtains a file asset with the specified index in the result set. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
indexnumberYesIndex of the file asset to obtain. The value starts from 0.
callbackAsyncCallback<T>YesCallback invoked to return the file asset obtained.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('getObjectByPositionDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  fetchResult.getObjectByPosition(0, (err, photoAsset) => {
    if (photoAsset != undefined) {
      console.info('photoAsset displayName: ', photoAsset.displayName);
    } else {
      console.error('photoAsset failed with err: ' + err);
    }
  });
}

getObjectByPosition

getObjectByPosition(index: number): Promise<T>

Obtains a file asset with the specified index in the result set. This API uses a promise to return the result.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
indexnumberYesIndex of the file asset to obtain. The value starts from 0.

Return value

TypeDescription
Promise<T>Promise used to return the file asset obtained.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('getObjectByPositionDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getObjectByPosition(0);
  console.info('photoAsset displayName: ', photoAsset.displayName);
}

getAllObjects

getAllObjects(callback: AsyncCallback<Array<T>>): void

Obtains all the file assets in the result set. This API uses an asynchronous callback to return the result.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<Array<T>>YesCallback invoked to return an array of all file assets in the result set.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('getAllObjectDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  fetchResult.getAllObjects((err, photoAssetList) => {
    if (photoAssetList != undefined) {
      console.info('photoAssetList length: ', photoAssetList.length);
    } else {
      console.error('photoAssetList failed with err:' + err);
    }
  });
}

getAllObjects

getAllObjects(): Promise<Array<T>>

Obtains all the file assets in the result set. This API uses a promise to return the result.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Return value

TypeDescription
Promise<Array<T>>Promise used to return an array of all file assets in the result set.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('getAllObjectDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
  let photoAssetList: Array<photoAccessHelper.PhotoAsset> = await fetchResult.getAllObjects();
  console.info('photoAssetList length: ', photoAssetList.length);
}

Album

Provides APIs to manage albums.

Attributes

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeReadableWritableDescription
albumTypeAlbumTypeYesNoType of the album.
albumSubtypeAlbumSubtypeYesNoSubtype of the album.
albumNamestringYesYes for a user album; no for a system album.Name of the album.
albumUristringYesNoURI of the album.
countnumberYesNoNumber of files in the album.
coverUristringYesNoURI of the cover file of the album.

getAssets

getAssets(options: FetchOptions, callback: AsyncCallback<FetchResult<PhotoAsset>>): void;

Obtains image and video assets. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.READ_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
optionsFetchOptionsYesOptions for fetching the albums.
callbackAsyncCallback<FetchResult<PhotoAsset>>YesCallback invoked to return the image and video assets obtained.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('albumGetAssetsDemoCallback');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let albumFetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  const albumList: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions);
  const album: photoAccessHelper.Album = await albumList.getFirstObject();
  album.getAssets(fetchOption, (err, albumFetchResult) => {
    if (albumFetchResult != undefined) {
      console.info('album getAssets successfully, getCount: ' + albumFetchResult.getCount());
    } else {
      console.error('album getAssets failed with error: ' + err);
    }
  });
}

getAssets

getAssets(options: FetchOptions): Promise<FetchResult<PhotoAsset>>;

Obtains image and video assets. This API uses a promise to return the result.

Required permissions: ohos.permission.READ_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
optionsFetchOptionsYesOptions for fetching the album files.

Return value

TypeDescription
Promise<FetchResult<PhotoAsset>>Promise used to return the image and video assets obtained.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

async function example() {
  console.info('albumGetAssetsDemoPromise');

  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let albumFetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  let fetchOption: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  const albumList: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions);
  const album: photoAccessHelper.Album = await albumList.getFirstObject();
  album.getAssets(fetchOption).then((albumFetchResult) => {
    console.info('album getPhotoAssets successfully, getCount: ' + albumFetchResult.getCount());
  }).catch((err: BusinessError) => {
    console.error('album getPhotoAssets failed with error: ' + err);
  });
}

commitModify

commitModify(callback: AsyncCallback<void>): void;

Commits the modification on the album attributes to the database. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
callbackAsyncCallback<void>YesCallback that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  console.info('albumCommitModifyDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let albumFetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  const albumList: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions);
  const album: photoAccessHelper.Album = await albumList.getFirstObject();
  album.albumName = 'hello';
  album.commitModify((err) => {
    if (err != undefined) {
      console.error('commitModify failed with error: ' + err);
    } else {
      console.info('commitModify successfully');
    }
  });
}

commitModify

commitModify(): Promise<void>;

Commits the modification on the album attributes to the database. This API uses a promise to return the result.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

async function example() {
  console.info('albumCommitModifyDemo');
  let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
  let albumFetchOptions: photoAccessHelper.FetchOptions = {
    fetchColumns: [],
    predicates: predicates
  };
  const albumList: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC, albumFetchOptions);
  const album: photoAccessHelper.Album = await albumList.getFirstObject();
  album.albumName = 'hello';
  album.commitModify().then(() => {
    console.info('commitModify successfully');
  }).catch((err: BusinessError) => {
    console.error('commitModify failed with error: ' + err);
  });
}

addAssets

addAssets(assets: Array<PhotoAsset>, callback: AsyncCallback<void>): void;

Adds image and video assets to an album. Before the operation, ensure that the image and video assets to add and the album exist. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
assetsArray<PhotoAsset>YesArray of the image and video assets to add.
callbackAsyncCallback<void>YesCallback that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  try {
    console.info('addAssetsDemoCallback');
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    let albumFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC);
    let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject();
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
    let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    album.addAssets([asset], (err) => {
      if (err === undefined) {
        console.info('album addAssets successfully');
      } else {
        console.error('album addAssets failed with error: ' + err);
      }
    });
  } catch (err) {
    console.error('addAssetsDemoCallback failed with error: ' + err);
  }
}

addAssets

addAssets(assets: Array<PhotoAsset>): Promise<void>;

Adds image and video assets to an album. Before the operation, ensure that the image and video assets to add and the album exist. This API uses a promise to return the result.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
assetsArray<PhotoAsset>YesArray of the image and video assets to add.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

async function example() {
  try {
    console.info('addAssetsDemoPromise');
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    let albumFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC);
    let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject();
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
    let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    album.addAssets([asset]).then(() => {
      console.info('album addAssets successfully');
    }).catch((err: BusinessError) => {
      console.error('album addAssets failed with error: ' + err);
    });
  } catch (err) {
    console.error('addAssetsDemoPromise failed with error: ' + err);
  }
}

removeAssets

removeAssets(assets: Array<PhotoAsset>, callback: AsyncCallback<void>): void;

Removes image and video assets from an album. The album and file resources must exist. This API uses an asynchronous callback to return the result.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
assetsArray<PhotoAsset>YesArray of the image and video assets to remove.
callbackAsyncCallback<void>YesCallback that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  try {
    console.info('removeAssetsDemoCallback');
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    let albumFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC);
    let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject();
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await album.getAssets(fetchOption);
    let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    album.removeAssets([asset], (err) => {
      if (err === undefined) {
        console.info('album removeAssets successfully');
      } else {
        console.error('album removeAssets failed with error: ' + err);
      }
    });
  } catch (err) {
    console.error('removeAssetsDemoCallback failed with error: ' + err);
  }
}

removeAssets

removeAssets(assets: Array<PhotoAsset>): Promise<void>;

Removes image and video assets from an album. The album and file resources must exist. This API uses a promise to return the result.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
assetsArray<PhotoAsset>YesArray of the image and video assets to remove.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

async function example() {
  try {
    console.info('removeAssetsDemoPromise');
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    let albumFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC);
    let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject();
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await album.getAssets(fetchOption);
    let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    album.removeAssets([asset]).then(() => {
      console.info('album removeAssets successfully');
    }).catch((err: BusinessError) => {
      console.error('album removeAssets failed with error: ' + err);
    });
  } catch (err) {
    console.error('removeAssetsDemoPromise failed with error: ' + err);
  }
}

recoverAssets

recoverAssets(assets: Array<PhotoAsset>, callback: AsyncCallback<void>): void;

Recovers image or video assets from the trash. Before the operation, ensure that the image or video assets exist in the trash. This API uses an asynchronous callback to return the result.

System API: This is a system API.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
assetsArray<PhotoAsset>YesArray of the image or video assets to recover.
callbackAsyncCallback<void>YesCallback that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  try {
    console.info('recoverAssetsDemoCallback');
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    let albumFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH);
    let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject();
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await album.getAssets(fetchOption);
    let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    album.recoverAssets([asset], (err) => {
      if (err === undefined) {
        console.info('album recoverAssets successfully');
      } else {
        console.error('album recoverAssets failed with error: ' + err);
      }
    });
  } catch (err) {
    console.error('recoverAssetsDemoCallback failed with error: ' + err);
  }
}

recoverAssets

recoverAssets(assets: Array<PhotoAsset>): Promise<void>;

Recovers image or video assets from the trash. Before the operation, ensure that the image or video assets exist in the trash. This API uses a promise to return the result.

System API: This is a system API.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
assetsArray<PhotoAsset>YesArray of the image or video assets to recover.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

async function example() {
  try {
    console.info('recoverAssetsDemoPromise');
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    let albumFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH);
    let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject();
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await album.getAssets(fetchOption);
    let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    album.recoverAssets([asset]).then(() => {
      console.info('album recoverAssets successfully');
    }).catch((err: BusinessError) => {
      console.error('album recoverAssets failed with error: ' + err);
    });
  } catch (err) {
    console.error('recoverAssetsDemoPromise failed with error: ' + err);
  }
}

deleteAssets

deleteAssets(assets: Array<PhotoAsset>, callback: AsyncCallback<void>): void;

Deletes image or video assets from the trash. Before the operation, ensure that the image or video assets exist in the trash. This API uses an asynchronous callback to return the result.

CAUTION
This operation is irreversible. The file assets deleted cannot be restored. Exercise caution when performing this operation.

System API: This is a system API.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
assetsArray<PhotoAsset>YesArray of the image or video assets to delete.
callbackAsyncCallback<void>YesCallback that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  try {
    console.info('deleteAssetsDemoCallback');
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    let albumFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH);
    let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject();
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await album.getAssets(fetchOption);
    let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    album.deleteAssets([asset], (err) => {
      if (err === undefined) {
        console.info('album deleteAssets successfully');
      } else {
        console.error('album deleteAssets failed with error: ' + err);
      }
    });
  } catch (err) {
    console.error('deleteAssetsDemoCallback failed with error: ' + err);
  }
}

deleteAssets

deleteAssets(assets: Array<PhotoAsset>): Promise<void>;

Deletes image or video assets from the trash. Before the operation, ensure that the image or video assets exist in the trash. This API uses a promise to return the result.

CAUTION
This operation is irreversible. The file assets deleted cannot be restored. Exercise caution when performing this operation.

System API: This is a system API.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
assetsArray<PhotoAsset>YesArray of the image or video assets to delete.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';
import { BusinessError } from '@ohos.base';

async function example() {
  try {
    console.info('deleteAssetsDemoPromise');
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    let albumFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.SYSTEM, photoAccessHelper.AlbumSubtype.TRASH);
    let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject();
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await album.getAssets(fetchOption);
    let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    album.deleteAssets([asset]).then(() => {
      console.info('album deleteAssets successfully');
    }).catch((err: BusinessError) => {
      console.error('album deleteAssets failed with error: ' + err);
    });
  } catch (err) {
    console.error('deleteAssetsDemoPromise failed with error: ' + err);
  }
}

setCoverUri

setCoverUri(uri: string, callback: AsyncCallback<void>): void;

Sets the album cover. This API uses an asynchronous callback to return the result.

NOTE
This API can be used to set the user album cover, but not the system album cover.

System API: This is a system API.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
uristringYesURI of the file to be set as the album cover.
callbackAsyncCallback<void>YesCallback that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.

Example

import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  try {
    console.info('setCoverUriDemoCallback');
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    let albumFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC);
    let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject();
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await album.getAssets(fetchOption);
    let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    album.setCoverUri(asset.uri, (err) => {
      if (err === undefined) {
        console.info('album setCoverUri successfully');
      } else {
        console.error('album setCoverUri failed with error: ' + err);
      }
    });
  } catch (err) {
    console.error('setCoverUriDemoCallback failed with error: ' + err);
  }
}

setCoverUri

setCoverUri(uri: string): Promise<void>;

Sets the album cover. This API uses a promise to return the result.

NOTE
This API can be used to set the user album cover, but not the system album cover.

System API: This is a system API.

Required permissions: ohos.permission.WRITE_IMAGEVIDEO

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

Parameters

NameTypeMandatoryDescription
uristringYesURI of the file to be set as the album cover.

Return value

TypeDescription
Promise<void>Promise that returns no value.

Error codes

For details about the error codes, see Universal Error Codes and File Management Error Codes.

IDError Message
202Called by non-system application.
401if parameter is invalid.
13900012Permission denied.
13900020Invalid argument.
14000011System inner fail.
Example
import dataSharePredicates from '@ohos.data.dataSharePredicates';

async function example() {
  try {
    console.info('setCoverUriDemoCallback');
    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
    let fetchOption: photoAccessHelper.FetchOptions = {
      fetchColumns: [],
      predicates: predicates
    };
    let albumFetchResult: photoAccessHelper.FetchResult<photoAccessHelper.Album> = await phAccessHelper.getAlbums(photoAccessHelper.AlbumType.USER, photoAccessHelper.AlbumSubtype.USER_GENERIC);
    let album: photoAccessHelper.Album = await albumFetchResult.getFirstObject();
    let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await album.getAssets(fetchOption);
    let asset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
    album.setCoverUri(asset.uri, (err) => {
      if (err === undefined) {
        console.info('album setCoverUri successfully');
      } else {
        console.error('album setCoverUri failed with error: ' + err);
      }
    });
  } catch (err) {
    console.error('setCoverUriDemoCallback failed with error: ' + err);
  }
}

MemberType

Enumerates the member types.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeReadableWritableDescription
numbernumberYesYesThe member is a number.
stringstringYesYesThe member is a string.
booleanbooleanYesYesThe member is a Boolean value.

PhotoType

Enumerates media file types.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
IMAGE1Image.
VIDEO2Video.

PhotoSubtype

Enumerates the PhotoAsset types.

System API: This is a system API.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
DEFAULT0Default (photo) type.
SCREENSHOT1Screenshot and screen recording file.

PositionType

Enumerates the file locations.

System API: This is a system API.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
LOCAL1 << 0Stored only on a local device.
CLOUD1 << 1Stored only on the cloud.

AlbumType

Enumerates the album types.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
USER0User album.
SYSTEM1024System album.

AlbumSubtype

Enumerate the album subtypes.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
USER_GENERIC1User album.
FAVORITE1025Favorites.
VIDEO1026Video album.
HIDDEN1027Hidden album.
System API: This is a system API.
TRASH1028Trash.
System API: This is a system API.
SCREENSHOT1029Album for screenshots and screen recording files.
System API: This is a system API.
CAMERA1030Album for photos and videos taken by the camera.
System API: This is a system API.
ANY2147483647Any album.

PhotoKeys

Defines the key information about an image or video file.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
URI'uri'URI of the file.
PHOTO_TYPE'media_type'Type of the file.
DISPLAY_NAME'display_name'File name displayed.
SIZE'size'File size.
DATE_ADDED'date_added'Date when the file was added. The value is the number of seconds elapsed since the Epoch time (00:00:00 UTC on January 1, 1970).
DATE_MODIFIED'date_modified'Date when the file content (not the file name) was last modified. The value is the number of seconds elapsed since the Epoch time.
DURATION'duration'Duration, in ms.
WIDTH'width'Image width, in pixels.
HEIGHT'height'Image height, in pixels.
DATE_TAKEN'date_taken'Date when the file (photo) was taken. The value is the number of seconds elapsed since the Epoch time.
ORIENTATION'orientation'Orientation of the image file.
FAVORITE'is_favorite'Whether the file is added to favorites.
TITLE'title'Title in the file.
POSITION'position'File location type.
System API: This is a system API.
DATE_TRASHED'date_trashed'Date when the file was deleted. The value is the number of seconds elapsed since the Epoch time. System API: This is a system API.
HIDDEN'hidden'Whether the file is hidden.
System API: This is a system API.
CAMERA_SHOT_KEY'camera_shot_key'Key for the Ultra Snapshot feature, which allows the camera to take photos or record videos with the screen off. (This parameter is available only for the system camera, and the key value is defined by the system camera.)
System API: This is a system API.
USER_COMMENT10+'user_comment'User comment information.
System API: This is a system API.
DATE_YEAR11+'date_year'Year when the file was created.
System API: This is a system API.
DATE_MONTH11+'date_month'Month when the file was created.
System API: This is a system API.
DATE_DAY11+'date_day'Date when the file was created.
System API: This is a system API.

AlbumKeys

Enumerates the key album attributes.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
URI'uri'URI of the album.
ALBUM_NAME'album_name'Name of the album.

PhotoCreateOptions

Defines the options for creating an image or video asset.

System API: This is a system API.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeMandatoryDescription
subtypePhotoSubtypeNoSubtype of the image or video.
cameraShotKeystringNoKey for the Ultra Snapshot feature, which allows the camera to take photos or record videos with the screen off. (This parameter is available only for the system camera, and the key value is defined by the system camera.)

CreateOptions

Defines the options for creating an image or video asset.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeMandatoryDescription
titlestringNoTitle of the image or video.

FetchOptions

Defines the options for fetching media files.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeReadableWritableDescription
fetchColumnsArray<string>YesYesOptions for fetching files based on the attributes in columns.
If this parameter is left empty, files are fetched by URI, name, and type (the specific field names vary with the file asset or album object) by default. In addition, an error will be reported if get is called to obtain other attributes of this object.
Example: fetchColumns: ['uri', 'title']
predicatesdataSharePredicates.DataSharePredicatesYesYesPredicates that specify the fetch criteria.

ChangeData

Defines the return value of the listener callback.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeReadableWritableDescription
typeNotifyTypeYesNoNotification type.
urisArray<string>YesNoAll URIs with the same NotifyType, which can be PhotoAsset or Album.
extraUrisArray<string>YesNoURIs of the changed files in the album.

NotifyType

Enumerates the notification event types.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
NOTIFY_ADD0A file asset or album is added.
NOTIFY_UPDATE1A file asset or album is updated.
NOTIFY_REMOVE2A file asset or album is removed.
NOTIFY_ALBUM_ADD_ASSET3A file asset is added to the album.
NOTIFY_ALBUM_REMOVE_ASSET4A file asset is removed from the album.

DefaultChangeUri

Enumerates the DefaultChangeUri subtypes.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
DEFAULT_PHOTO_URI'file://media/Photo'Default PhotoAsset URI. The PhotoAsset change notifications are received based on this parameter and forSubUri{true}.
DEFAULT_ALBUM_URI'file://media/PhotoAlbum'Default album URI. Album change notifications are received based on this parameter and forSubUri{true}.

PhotoViewMIMETypes

Enumerates the media file types that can be selected.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameValueDescription
IMAGE_TYPE'image/*'Image.
VIDEO_TYPE'video/*'Video.
IMAGE_VIDEO_TYPE'*/*'Image and video.

PhotoSelectOptions

Defines the options for selecting images or videos.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeMandatoryDescription
MIMETypePhotoViewMIMETypesNoAvailable media file types. IMAGE_VIDEO_TYPE is used by default.
maxSelectNumbernumberNoMaximum number of media files that can be selected. The default value is 50, and the maximum value is 500.

PhotoSelectResult

Defines information about the images or videos selected.

System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core

NameTypeReadableWritableDescription
photoUrisArray<string>YesYesURIs of the images or videos selected. The URI array can be used only by calling photoAccessHelper.getAssets with temporary authorization. For details about how to use the media file URI, see [Using a Media File URI] (../../file-management/user-file-uri-intro.md#using-a-media-file-uri).
isOriginalPhotobooleanYesYesWhether the selected media file is the original image.

你可能感兴趣的鸿蒙文章

harmony 鸿蒙APIs

harmony 鸿蒙System Common Events (To Be Deprecated Soon)

harmony 鸿蒙System Common Events

harmony 鸿蒙API Reference Document Description

harmony 鸿蒙Enterprise Device Management Overview (for System Applications Only)

harmony 鸿蒙BundleStatusCallback

harmony 鸿蒙@ohos.bundle.innerBundleManager (innerBundleManager)

harmony 鸿蒙@ohos.distributedBundle (Distributed Bundle Management)

harmony 鸿蒙@ohos.bundle (Bundle)

harmony 鸿蒙@ohos.enterprise.EnterpriseAdminExtensionAbility (EnterpriseAdminExtensionAbility)

  • 所属分类: 后端技术
  • 本文标签: 软件 鸿蒙
  • 版权声明: 本文链接 https://seaxiang.com/blog/01b8eb18838d41fbb4e8264467289149