@ohos.file.PhotoPickerComponent (PhotoPickerComponent)
You can embed the PhotoPickerComponent in your application's layout to let users pick images or videos without requiring extra permissions. Once the users have made their selection, your application gets read-only access to the chosen images or videos.
Note that the PhotoPickerComponent does not support nesting. Additionally, avoid overlaying components with the overlay attribute on top of the PhotoPickerComponent, as this will prevent the PhotoPickerComponent from receiving gesture events.
Once embedded, users can directly select images or videos within the PhotoPickerComponent.
NOTE
- This component is supported since API version 12. Updates will be marked with a superscript to indicate their earliest API version.
- This component does not support same-layer rendering.
Modules to Import
// In versions earlier than API version 23, you need to use the 'import { api1, api2,... } from @ohos.file.PhotoPickerComponent' import mode.
import {
PhotoPickerComponent, PickerController, PickerOptions,
DataType, BaseItemInfo, ItemInfo, PhotoBrowserInfo, ItemType, ClickType,
MaxCountType, PhotoBrowserRange, PhotoBrowserUIElement,
ItemsDeletedCallback, ExceedMaxSelectedCallback, CurrentAlbumDeletedCallback, SingleLineConfig,
BadgeConfig, PreselectedInfo, SaveMode, BadgeType, VideoPlayerState, ItemDisplayRatio
} from '@kit.MediaLibraryKit';
Attributes
The universal attributes are supported.
PhotoPickerComponent
PhotoPickerComponent({ pickerOptions?: PickerOptions, onSelect?: (uri: string) => void, onDeselect?: (uri: string) => void, onItemClicked?: (itemInfo: ItemInfo, clickType: ClickType) => boolean, onItemClickedNotify?: ItemClickedNotifyCallback, onEnterPhotoBrowser?: (photoBrowserInfo: PhotoBrowserInfo) => boolean, onExitPhotoBrowser?: (photoBrowserInfo: PhotoBrowserInfo) => boolean, onPickerControllerReady?: () => void, onPhotoBrowserChanged?: (browserItemInfo: BaseItemInfo) => boolean, onSelectedItemsDeleted?: ItemsDeletedCallback, onExceedMaxSelected?: ExceedMaxSelectedCallback, onCurrentAlbumDeleted?: CurrentAlbumDeletedCallback, onVideoPlayStateChanged?: videoPlayStateChangedCallback, pickerController: PickerController })
Allows the application to access images or videos in the user directory without any permission.
NOTE If the PhotoPickerComponent is used with the Tabs component, the swipe gestures of the Tabs component conflict with those of the photo browser page.
To prevent this problem, you can disable the swipe operation for the Tabs component in onEnterPhotoBrowser() and enable it in onExitPhotoBrowser(). This conflict will be resolved in later versions.
Decorator: @Component
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Decorator Type | Description |
|---|---|---|---|---|
| pickerOptions | PickerOptions | No | - | Picker configuration parameters. Atomic service API: This API can be used in atomic services since API version 12. |
| onSelect | (uri: string) => void | No | - | Callback to be invoked when an image is selected by using PhotoPickerComponent. This callback returns the URI of the image selected to the application. Atomic service API: This API can be used in atomic services since API version 12. |
| onDeselect | (uri: string) => void | No | - | Callback to be invoked when an image is deselected by using PhotoPickerComponent. This callback returns the URI of the image deselected to the application. Atomic service API: This API can be used in atomic services since API version 12. |
| onItemClicked | (itemInfo: ItemInfo, clickType: ClickType) => boolean | No | - | Callback to be invoked when an item in a PhotoPickerComponent is clicked. For an image (thumbnail item), if true is returned, the image is selected. Otherwise, the image is not selected and the URI is not granted with the permission. For a camera item, if true is returned, the system camera is started. Otherwise, the camera is not started and the application handles the request. Atomic service API: This API can be used in atomic services since API version 12. |
| onItemClickedNotify23+ | ItemClickedNotifyCallback | No | - | Callback to be invoked when an item in a PhotoPickerComponent is clicked. The application can execute the logic of determining whether the item is selected. This parameter must be used together with the addData method to select or deselect the item based on the value of ADD_ITEM_CLICK_RESULT. If no click result is set, the authorization is canceled 2 seconds later or when the PhotoPickerComponent is closed. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 23. |
| onPinchGridSwitched23+ | PinchGridSwitchedCallback | No | - | Callback to be invoked when a grid is pinched. This callback is triggered only when GridPinchModeType is set to FULL_FUNCTION_GRID. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 23. |
| onEnterPhotoBrowser | (photoBrowserInfo: PhotoBrowserInfo) => boolean | No | - | Callback to be invoked when the photo browser page is displayed. The callback returns photo browser information to the application. No special processing is performed on the return value. Atomic service API: This API can be used in atomic services since API version 12. |
| onExitPhotoBrowser | (photoBrowserInfo: PhotoBrowserInfo) => boolean | No | - | Callback to be invoked when the photo browser page exits. The callback returns photo browser information to the application. No special processing is performed on the return value. Atomic service API: This API can be used in atomic services since API version 12. |
| onPickerControllerReady | () => void | No | - | Callback to be invoked when pickerController is available. The PickerController APIs can be called only after this callback is invoked. Atomic service API: This API can be used in atomic services since API version 12. |
| onPhotoBrowserChanged | (browserItemInfo: BaseItemInfo) => boolean | No | - | Callback to be invoked when the photo browser page is swiped left or right. The callback returns photo browser information to the application. The setting takes effect only in multi-selection mode. No special processing is performed on the return value. Atomic service API: This API can be used in atomic services since API version 12. |
| onSelectedItemsDeleted13+ | ItemsDeletedCallback | No | - | Callback to be invoked when the selected items are deleted. This callback returns information about the deleted items to the application. Atomic service API: This API can be used in atomic services since API version 13. |
| onExceedMaxSelected13+ | ExceedMaxSelectedCallback | No | - | Callback to be invoked when the number of selected media assets exceeds the limit (maximum number of selected images, selected videos, or selected items). - If the number of selected images reaches the maximum but does not reach the maximum count of selected items, exceedMaxCountType in the callback is MaxCountType.PHOTO_MAX_COUNT. - If the number of selected videos reaches the maximum but does not reach the maximum count of selected items, exceedMaxCountType in the callback is MaxCountType.VIDEO_MAX_COUNT. - If the number of selected media assets reaches the maximum count of selected items, exceedMaxCountType in the callback is MaxCountType.TOTAL_MAX_COUNT. Atomic service API: This API can be used in atomic services since API version 13. |
| onCurrentAlbumDeleted13+ | CurrentAlbumDeletedCallback | No | - | Callback to be invoked when the current album is deleted. The album is specified by currentAlbumUri in pickerController.setData(DataType.SET_ALBUM_URI, currentAlbumUri). To refresh the grid page to display the default album after the current album is deleted, you can set the title bar name to the default album name, for example, Photos and videos, Photos, or Videos, and call pickerController.setData(DataType.SET_ALBUM_URI, '') with an empty string. Atomic service API: This API can be used in atomic services since API version 13. |
| onVideoPlayStateChanged14+ | videoPlayStateChangedCallback | No | - | Callback to be invoked when the video playback state on a photo browser page changes. Atomic service API: This API can be used in atomic services since API version 14. |
| pickerController | PickerController | Yes | @ObjectLink | Instance used to send data to the PhotoPickerComponent. Atomic service API: This API can be used in atomic services since API version 12. |
| onMovingPhotoBadgeStateChanged22+ | MovingPhotoBadgeStateChangedCallback | No | - | Callback to be invoked when the moving photo effect of the PhotoPickerComponent is enabled or disabled. This callback reports the image's URI and its new moving photo badge state to the application. Atomic service API: This API can be used in atomic services since API version 22. |
| onScrollStopAtStart23+ | ScrollStopAtStartCallback | No | - | Callback to be invoked when the user stops scrolling and is positioned at the beginning of the grid content in the PhotoPickerComponent. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 23. |
| onScrollStopAtEnd23+ | ScrollStopAtEndCallback | No | - | Callback to be invoked when the user stops scrolling and is positioned at the end of the grid content in the PhotoPickerComponent. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 23. |
| onPhotoBrowserChangeStart23+ | PhotoBrowserChangeStartCallback | No | - | Callback to be invoked when a grid view switches to the photo browser page or the photo browser page is switched. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 23. |
| onError23+ | ErrorCallback | No | - | Callback to be invoked when an error occurs during the use of the PhotoPickerComponent. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 23. |
PickerOptions
Describes the configuration of a Picker. It inherits from photoAccessHelper.BaseSelectOptions.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| checkBoxColor | string | No | Yes | Background color of the check box. The value is an 8-digit hexadecimal color code. Atomic service API: This API can be used in atomic services since API version 12. |
| backgroundColor | string | No | Yes | Background color of the Picker grid page. The value is an 8-digit hexadecimal color code. Atomic service API: This API can be used in atomic services since API version 12. |
| isRepeatSelectSupported | boolean | No | Yes | Whether a single image can be repeatedly selected. The value true means that a single image can be repeatedly selected. The default value is false. Atomic service API: This API can be used in atomic services since API version 12. |
| checkboxTextColor | string | No | Yes | Text color in the check box. The value is an 8-digit hexadecimal color code. (This parameter is supported since API version 19. In earlier versions, the system defaults to white.) Atomic service API: This API can be used in atomic services since API version 12. |
| photoBrowserBackgroundColorMode | PickerColorMode | No | Yes | Background color of the photo browser page. The options are AUTO, LIGHT, and DARK. The default value is AUTO. Atomic service API: This API can be used in atomic services since API version 12. |
| maxSelectedReminderMode | ReminderMode | No | Yes | Mode of the reminder when the number of selected items reaches the maximum. The options are NONE, TOAST, and MASK. The default value TOAST. Atomic service API: This API can be used in atomic services since API version 12. |
| orientation | PickerOrientation | No | Yes | Sliding preview direction of the grid page. The options are HORIZONTAL and VERTICAL. The default value is VERTICAL. (This parameter is supported since API version 20. In earlier versions, the system defaults to vertical.) Atomic service API: This API can be used in atomic services since API version 12. |
| selectMode | SelectMode | No | Yes | Select mode, which can be SINGLE_SELECT or MULTI_SELECT. The default value is MULTI_SELECT. Atomic service API: This API can be used in atomic services since API version 12. |
| maxPhotoSelectNumber | number | No | Yes | Maximum number of images that can be selected. The maximum value is 500, which is limited by MaxSelected. The default value is 500. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 12. |
| maxVideoSelectNumber | number | No | Yes | Maximum number of videos that can be selected. The maximum value is 500, and it is restricted by the maximum number of media files that can be selected in the system. The default value is 500. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 12. |
| isSlidingSelectionSupported13+ | boolean | No | Yes | Whether sliding selection (selecting multiple items by sliding finger across the screen) is supported. The value true means that sliding selection is supported. The default value is false. This parameter is not available for repeat selection. Atomic service API: This API can be used in atomic services since API version 13. |
| photoBrowserCheckboxPosition13+ | [number, number] | No | Yes | Position of the check box on the photo browser page. The first parameter specifies the offset in the X direction, and the second parameter specifies the offset in the Y direction. The value range is [0, 1], which indicates the offset (from 0% to 100%) to the upper-left corner of the component. The default value is [0, 0]. Atomic service API: This API can be used in atomic services since API version 13. |
| gridMargin14+ | Margin | No | Yes | Margin of the component on a grid page. Atomic service API: This API can be used in atomic services since API version 14. |
| photoBrowserMargin14+ | Margin | No | Yes | Margin of the component on a photo browser page. Atomic service API: This API can be used in atomic services since API version 14. |
| singleLineConfig20+ | SingleLineConfig | No | Yes | Single-line display mode of a grid page. In single-line mode, the component does not provide functions for viewing a larger image. The component does not support callbacks related to large images, and the PickerController does not support APIs related to large images, making API calls ineffective. Atomic service API: This API can be used in atomic services since API version 20. |
| uiComponentColorMode20+ | PickerColorMode | No | Yes | Picker color mode. Dark/Light color mode (excluding the background color) of other components on the Picker grid page, including the search box, camera entry, safety tips for using Gallery, and recommendation bubble. This attribute is usually used together with backgroundColor. The default value is PickerColorMode.AUTO, which follows the system's dark/light color mode. When setting this attribute, avoid using PickerColorMode.LIGHT with a dark backgroundColor, as it may make components or text hard to see. Avoid using PickerColorMode.DARK with a light backgroundColor for the same reason. Atomic service API: This API can be used in atomic services since API version 20. |
| gridStartOffset20+ | number | No | Yes | Space between the top of the component and the first row of the grid thumbnail. The default value is 0, in vp. Atomic service API: This API can be used in atomic services since API version 20. |
| gridEndOffset20+ | number | No | Yes | Space between the bottom of the component and the last row of the grid thumbnail. The default value is 0, in vp. Atomic service API: This API can be used in atomic services since API version 20. |
| pickerIndex21+ | number | No | Yes | Unique serial number used to distinguish different picker components. The default value is -1, indicating that no distinction is made. Atomic service API: This API can be used in atomic services since API version 21. |
| preselectedInfos21+ | Array<PreselectedInfo> | No | Yes | Array of information previously selected by the user, so that the PhotoPickerComponent identified by pickerIndex can display the information. Atomic service API: This API can be used in atomic services since API version 21. |
| badgeConfig21+ | BadgeConfig | No | Yes | Badge configuration. Currently, the PhotoPickerComponent supports only one type of badge. For details, see BadgeType. Atomic service API: This API can be used in atomic services since API version 21. |
| isSlidingSupported23+ | boolean | No | Yes | Whether scrolling in the PhotoPickerComponent is enabled. The value true means that scrolling is not blocked and the component responds to user scroll gestures. The value false means that scrolling is blocked and the component does not respond to user scroll gestures. The default value is true. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 23. |
| edgeEffect23+ | EdgeEffect | No | Yes | Scrolling effect when the Picker grid page reaches the edge. The default value is EdgeEffect.Spring. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 23. |
| appAlbumFilters23+ | Array<string> | No | Yes | Used to display only the album content corresponding to the specified bundle name. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 23. |
| backgroundOpacity24+ | number | No | Yes | Background opacity of the picker. The value range is [0, 1]. 0 indicates completely transparent, and 1 indicates completely opaque. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 24. |
ItemsDeletedCallback13+
type ItemsDeletedCallback = (baseItemInfos: Array<BaseItemInfo>) => void
Called when the selected items are deleted.
Atomic service API: This API can be used in atomic services since API version 13.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| baseItemInfos | Array<BaseItemInfo> | Yes | Basic information about the selected items. |
ExceedMaxSelectedCallback13+
type ExceedMaxSelectedCallback = (exceedMaxCountType: MaxCountType) => void
Called when items are selected after the maximum count has been reached.
Atomic service API: This API can be used in atomic services since API version 13.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| exceedMaxCountType | MaxCountType | Yes | Type of the maximum count that has been reached. It can be the maximum count of selected images, maximum count of selected videos, or maximum count of selected images and videos. |
CurrentAlbumDeletedCallback13+
type CurrentAlbumDeletedCallback = () => void
Called when the current album is deleted.
Atomic service API: This API can be used in atomic services since API version 13.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
videoPlayStateChangedCallback14+
type videoPlayStateChangedCallback = (state: VideoPlayerState) => void
Callback to be invoked when the video playback state on a photo browser page changes.
Atomic service API: This API can be used in atomic services since API version 14.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| state | VideoPlayerState | Yes | Enumerates the video playback states. |
MovingPhotoBadgeStateChangedCallback22+
type MovingPhotoBadgeStateChangedCallback = (uri: string, state: photoAccessHelper.MovingPhotoBadgeStateType) => void
Callback to be invoked when the moving photo effect of the PhotoPickerComponent is enabled or disabled.
Atomic service API: This API can be used in atomic services since API version 22.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| uri | string | Yes | URI of the moving photo. |
| state | photoAccessHelper.MovingPhotoBadgeStateType | Yes | State of the moving photo badge. |
ScrollStopAtStartCallback23+
type ScrollStopAtStartCallback = () => void
Callback to be invoked when the user stops scrolling and is positioned at the beginning of the grid content in the PhotoPickerComponent.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
ItemClickedNotifyCallback23+
type ItemClickedNotifyCallback = (itemInfo: ItemInfo, clickType: ClickType) => void
Callback to be invoked when an item in a PhotoPickerComponent is clicked.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| itemInfo | ItemInfo | Yes | Type of the clicked item, which can be a thumbnail item or a camera item. |
| clickType | ClickType | Yes | Enumerates the click operation types. |
Example:
import {
ClickResult,
ClickType,
DataType,
ItemInfo,
ItemClickedNotifyCallback,
PhotoPickerComponent,
PickerController,
PickerOptions,
} from '@kit.MediaLibraryKit';
import { router } from '@kit.ArkUI';
const DOMAIN = 0x0000;
const TAG: string = 'clickedNotifyDemo';
interface Checks {
isOnClicked: boolean;
isOnClickedNotify: boolean;
}
export interface ClickResultEx {
uri: string,
isSelected: boolean,
}
@Entry
@Component
struct PickerPage {
@State pickerController: PickerController = new PickerController();
private pickerOptions: PickerOptions = new PickerOptions();
@State currentUri: string = '';
@State currentState: number = 0;
@State clickedUris: Map<string, ClickResultEx> = new Map();
private isOnClicked: boolean = false;
private isOnClickedNotify: boolean = false;
onClicked: (itemInfo: ItemInfo, clickType: ClickType) => boolean = (itemInfo: ItemInfo, clickType: ClickType) => {
return true;
};
// When an item is clicked, the code checks whether the corresponding URI is valid. An invalid URI is ignored.
// Then, the code checks whether the URI already exists in clickedUris. If not, it creates a record and sets the isSelected property to true.
// If yes, the code updates the isSelected property of the record to true.
// After the data is saved, clicking the setClickResult button will call addData(SET_ITEM_CLICK_RESULT) to set the corresponding item to the selected state.
onClickedNotify: ItemClickedNotifyCallback = (itemInfo: ItemInfo, clickType: ClickType) => {
if (!itemInfo.uri) {
return;
}
let clickResult = this.clickedUris.get(itemInfo.uri);
if (!clickResult) {
clickResult = {
uri: itemInfo.uri,
isSelected: true,
};
} else {
clickResult.isSelected = true;
}
this.clickedUris.set(itemInfo.uri, clickResult);
};
aboutToAppear(): void {
let params = router.getParams() as Checks;
this.pickerOptions.isSlidingSelectionSupported = true;
this.pickerOptions.isSearchSupported = false;
this.isOnClicked = params.isOnClicked;
// Obtain parameters from the index.ets page.
this.isOnClickedNotify = params.isOnClickedNotify;
this.pickerOptions.maxPhotoSelectNumber = 500;
}
// Obtain the URIs from this.clickedUris, which will be used when pickerController.addData() is called to set the item to be selected.
getClickedUris(): ClickResult[] {
let uris: ClickResultEx[] = [];
this.clickedUris.forEach((uri, index) => {
uris.push(uri)
})
return uris;
}
build() {
Column() {
Row() {
// Call the photo picker component.
PhotoPickerComponent({
pickerOptions: this.pickerOptions,
pickerController: this.pickerController,
onItemClicked: this.isOnClicked ? this.onClicked : undefined,
onItemClickedNotify: this.isOnClickedNotify ? this.onClickedNotify : undefined,
onSelect: (uri: string) => {},
onDeselect: (uri: string) => {}
})
}.height('50%')
Row() {
Column() {
Text('Selected assets')
ForEach(this.getClickedUris(), (uri: ClickResult) => {
Row() {
// You can remove or add a selection.
Checkbox({ name: "OnClick" })
.select(uri.isSelected)
.onChange((checked: boolean) => {
let clickResult = this.clickedUris.get(uri.uri);
if (!clickResult) {
clickResult = {
uri: uri.uri,
isSelected: checked
};
} else {
clickResult.isSelected = checked;
}
if (uri.uri !== 'abnormal') {
this.clickedUris.set(uri.uri, clickResult);
}
}).margin({ right: 5 })
Text(uri.uri.slice(-30)).margin({right: 5}).width(150)
// Remove the selected item from this.clickeduris.
Button('Delete').onClick(() => {
this.clickedUris.delete(uri.uri);
})
// The following code is an example of an exception scenario. When an abnormal URI is passed, the item selected by Picker does not take effect.
Button('Abnormal').onClick(() => {
let clickResult = this.clickedUris.get(uri.uri);
if (clickResult) {
let oldClickUri = clickResult.uri;
clickResult.uri = 'abnormal'
this.clickedUris.set(oldClickUri, clickResult)
}
})
}.width('100%')
})
}
}.height('20%')
Row() {
// Send URI (SET_ITEM_CLICK_RESULT).
Button('Set ClickResult')
.onClick(() => {
this.pickerController.addData(DataType.SET_ITEM_CLICK_RESULT, this.getClickedUris())
})
}.height('10%')
}
.height('100%')
.width('100%')
}
}
ScrollStopAtEndCallback23+
type ScrollStopAtEndCallback = () => void
Callback to be invoked when the user stops scrolling and is positioned at the end of the grid content in the PhotoPickerComponent.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
PhotoBrowserChangeStartCallback23+
type PhotoBrowserChangeStartCallback = (targetPhotoInfo: BaseItemInfo) => void
Callback to be invoked when the moving photo effect of the PhotoPickerComponent is enabled or disabled.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| targetPhotoInfo | BaseItemInfo | Yes | Basic information about the selected items. |
PinchGridSwitchedCallback23+
type PinchGridSwitchedCallback = (gridLevel: photoAccessHelper.GridLevel) => void
Callback to be invoked when a user pinches a grid component.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| gridLevel | photoAccessHelper.GridLevel | Yes | Number of columns in the grid. |
ErrorCallback23+
type ErrorCallback = (pickerError: PickerError) => void
Callback to be invoked when an error occurs in the PhotoPickerComponent.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| pickerError | PickerError | Yes | Basic information about the error. |
PickerController
Defines an instance used to send data to the PhotoPickerComponent.
Decorator Type: @Observed
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
setData
setData(dataType: DataType, data: Object): void
Sends data of the specified type to the PhotoPickerComponent.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| dataType | DataType | Yes | Type of the data to send. |
| data | Object | Yes | Data to send. |
addData21+
addData(dataType: DataType, data: Object): void
Sends additional configuration data to the PhotoPickerComponent. The DataType parameter identifies the type of data to send, and only the SET_BADGE_CONFIGS type is supported currently.
Atomic service API: This API can be used in atomic services since API version 21.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| dataType | DataType | Yes | Type of additional configuration data to send. |
| data | Object | Yes | Additional configuration data to send. |
deleteData21+
deleteData(dataType: DataType, data: Object): void
Sends removal configuration data to the PhotoPickerComponent. The DataType parameter identifies the type of data to send, and only the SET_BADGE_CONFIGS type is supported currently.
Atomic service API: This API can be used in atomic services since API version 21.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| dataType | DataType | Yes | Type of removal configuration data to send. |
| data | Object | Yes | Removal configuration data to send. |
setMaxSelected
setMaxSelected(maxSelected: MaxSelected): void
Sets the maximum number of images, videos, or images and videos that can be selected in real time.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| maxSelected | MaxSelected | Yes | Maximum number of media assets that can be selected at a time. |
setPhotoBrowserItem
setPhotoBrowserItem(uri: string, photoBrowserRange?: PhotoBrowserRange): void
Switches from the PhotoPickerComponent to the photo browser page or from the photo browser page to the image to be viewed.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| uri | string | Yes | URI of the image to view. Only the images selected by the user are supported. |
| photoBrowserRange | PhotoBrowserRange | No | View range on the photo browser page. The value can be ALL or SELECTED_ONLY. The default value is ALL, which means to view all images and videos. |
exitPhotoBrowser13+
exitPhotoBrowser(): void
Exits the photo browser page.
Atomic service API: This API can be used in atomic services since API version 13.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
setPhotoBrowserUIElementVisibility13+
setPhotoBrowserUIElementVisibility(elements: Array<PhotoBrowserUIElement>, isVisible: boolean): void
Sets whether other UI elements are visible on the photo browser page. By default, other UI elements are visible.
Atomic service API: This API can be used in atomic services since API version 13.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| elements | Array<PhotoBrowserUIElement> | Yes | Other UI elements on the photo browser page. |
| isVisible | boolean | Yes | Whether the specified UI elements are visible. The value true means that they are visible. The default value is false. |
replacePhotoPickerPreview15+
replacePhotoPickerPreview(originalUri: string, newUri: string, callback: AsyncCallback<void>): void
Replaces the image selected by the user in the PhotoPickerComponent with the image edited by the application.
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| originalUri | string | Yes | URI of the original image, which will be replaced. |
| newUri | string | Yes | URI of the new image. The new image is temporarily stored in the application sandbox path. Therefore, this URI specifies a directory in the application sandbox path. |
| callback | AsyncCallback<void> | Yes | Callback invoked when image replacement is complete. |
saveTrustedPhotoAssets15+
saveTrustedPhotoAssets(trustedUris: Array<string>, callback: AsyncCallback<Array<string>>, configs?: Array<photoAccessHelper.PhotoCreationConfig>, saveMode?: SaveMode): void
Saves files in a URI list. Generally, this API is used together with replacePhotoPickerPreview to save the new images or videos in the application sandbox path to Gallery.
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| trustedUris | Array<string> | Yes | URIs of the images or videos in the application sandbox path. Generally, trustedUris comes from newUri of new images generated by replacePhotoPickerPreview. |
| callback | AsyncCallback<Array<string>> | Yes | URIs of the new files in Gallery. |
| configs | Array<photoAccessHelper.PhotoCreationConfig> | No | Configuration parameters corresponding to the original files. NOTE 1. If a subtype option is passed, the configuration does not take effect. Only DEFAULT images can be saved. By default, the values of title, fileNameExtension, and photoType of mediaItem corresponding to trustedUris are used, and the value of subtype is fixed to DEFAULT. 2. This parameter does not take effect when SaveMode is set to OVERWRITE. |
| saveMode | SaveMode | No | Mode for saving the files. By default, the SAVE_AS mode is used to save the files as new files. |
updatePickerOptions22+
updatePickerOptions(updateConfig: UpdatablePickerConfigs): Promise<void>
Updates the attributes of the PhotoPickerComponent. This API uses a promise to return the result.
Atomic service API: This API can be used in atomic services since API version 22.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| updateConfig | UpdatablePickerConfigs | Yes | New attributes, which are a subset of PickerOptions. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
saveTrustedPhotoAssetsEx23+
saveTrustedPhotoAssetsEx(trustedUris: Array<string>,settings?: Array<photoAccessHelper.CreationSetting>, saveMode?: SaveMode): Promise<Array<string>>
Saves files in a URI list. This API uses a promise to return the result.
NOTE
This API is usually used together with replacePhotoPickerPreview to save the new images or videos in the application sandbox path to Gallery.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| trustedUris | Array<string> | Yes | URIs of the images or videos in the application sandbox path. trustedUris is usually the newUri of the images or videos in the application sandbox path that are successfully replaced by replacePhotoPickerPreview. |
| settings | Array<photoAccessHelper.CreationSetting> | No | Configuration parameters corresponding to the original files. By default, the title, fileNameExtension, and photoType values of mediaItem corresponding to trustedUris are used. |
| saveMode | SaveMode | No | Mode for saving images or videos. By default, the SAVE_AS mode is used to save the files as new files. |
Return value
| Type | Description |
|---|---|
| Promise<Array<string>> | Promise used to return the URI of the new asset. |
setMovingPhotoState23+
setMovingPhotoState(movingPhotoState: photoAccessHelper.MovingPhotoBadgeStateType): Promise<void>
Sets the state of the moving photo on the photo browser page. This API uses a promise to return the result.
This parameter takes effect only on the photo browser page. NOT_MOVING_PHOTO cannot be set.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
Parameters
| Name | Type | Mandatory | Description |
|---|---|---|---|
| movingPhotoState | photoAccessHelper.MovingPhotoBadgeStateType | Yes | State of the moving photo on the photo browser page. |
Error codes
For details about the error codes, see Media Library Error Codes.
| ID | Error Message |
|---|---|
| 23800151 | Scene parameters validate failed, possible causes: 1. An invalid enumeration value was passed. Only MOVING_PHOTO_ENABLE and MOVING_PHOTO_DISABLE are supported for configuration |
| 23800202 | Invalid call context. Possible causes: 1. The API is called outside the photo browsing scenario. 2. The API is called when isMovingPhotoBadgeShown is already set to true. |
Return value
| Type | Description |
|---|---|
| Promise<void> | Promise that returns no value. |
BaseItemInfo
Represents basic image and video information.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| uri | string | No | Yes | URI of the image or video. This parameter is supported only when ItemType is set to THUMBNAIL. Otherwise, it is left empty. Atomic service API: This API can be used in atomic services since API version 12. |
| mimeType | string | No | Yes | MIME type of the image or video. This parameter is supported only when ItemType is set to THUMBNAIL. Otherwise, it is left empty. Atomic service API: This API can be used in atomic services since API version 12. |
| width | number | No | Yes | Width of the image or video, in px. This parameter is supported only when ItemType is set to THUMBNAIL. Otherwise, it is left empty. Atomic service API: This API can be used in atomic services since API version 12. |
| height | number | No | Yes | Height of the image or video, in px. This parameter is supported only when ItemType is set to THUMBNAIL. Otherwise, it is left empty. Atomic service API: This API can be used in atomic services since API version 12. |
| size | number | No | Yes | Size of the image or video, in bytes. This parameter is supported only when ItemType is set to THUMBNAIL. Otherwise, it is left empty. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 12. |
| duration | number | No | Yes | Video duration, in milliseconds. This parameter is supported only when ItemType is set to THUMBNAIL. Otherwise, it is left empty. Atomic service API: This API can be used in atomic services since API version 12. |
| photoSubType21+ | photoAccessHelper.PhotoSubtype | No | Yes | Subtype of the photo. The options are DEFAULT, MOVING_PHOTO, and BURST. The default value is DEFAULT (0). Atomic service API: This API can be used in atomic services since API version 21. |
| dynamicRangeType21+ | photoAccessHelper.DynamicRangeType | No | Yes | Dynamic range type of the media file. The options are HDR and SDR. For moving photos, this parameter specifies the dynamic range type of the cover image. Atomic service API: This API can be used in atomic services since API version 21. |
| orientation21+ | number | No | Yes | Image or video direction information. 1: TOP-left: The image is not rotated. 2: TOP-right: The image is flipped horizontally. 3: Bottom-right: The image is rotated by 180°. 4: Bottom-left: The image is flipped vertically. 5: Left-top: The image is flipped horizontally and then rotated clockwise by 270°. 6: Right-top: The image is rotated clockwise by 90°. 7: Right-bottom: The image is vertically flipped and then rotated clockwise by 90°. 8: Left-bottom: The image is rotated clockwise by 270°. Images with mirroring information retain their original width and height attributes regardless of rotation, whereas images without such information have these attributes updated to reflect the post-rotation dimensions. Atomic service API: This API can be used in atomic services since API version 21. |
| movingPhotoBadgeState22+ | photoAccessHelper.MovingPhotoBadgeStateType | No | Yes | State of the moving photo badge. This parameter is supported only when ItemType is set to THUMBNAIL. Otherwise, it is left empty. Atomic service API: This API can be used in atomic services since API version 22. |
| videoMode22+ | photoAccessHelper.VideoMode | No | Yes | Log mode of a video file. Atomic service API: This API can be used in atomic services since API version 22. |
ItemInfo
Represents the image and video information. It inherits from BaseItemInfo, adding the parameter itemType.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| itemType | ItemType | No | Yes | Type of the item, which can be THUMBNAIL or CAMERA. |
PhotoBrowserInfo
Represents information about the photo browser page.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| animatorParams | AnimatorParams | No | Yes | Animation for entering or exiting the photo browser page. |
AnimatorParams
Defines animation parameters for entering or exiting the photo browser page.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| duration | number | No | Yes | Animation duration, in ms. |
| curve | Curve | ICurve | string | No | Yes | Animation curve. |
MaxSelected
Represents the maximum number of media assets that can be selected at a time.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| data | Map<MaxCountType, number> | No | Yes | Maximum number of media assets (images, videos, or both) that can be selected at a time. |
SingleLineConfig20+
Represents the single-line display mode. In single-line mode, the component does not provide functions for viewing a larger image. The component does not support callbacks related to large images, and the PickerController does not support APIs related to large images, making API calls ineffective.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| itemDisplayRatio | ItemDisplayRatio | No | Yes | Aspect ratio for grid display. Both 1:1 and the original image aspect ratio are supported. The default value is 1:1. |
| itemBorderRadius | Length | BorderRadiuses | LocalizedBorderRadiuses | No | Yes | Rounded corner radius for grid items. |
| itemGap | Length | No | Yes | Spacing between grid items. |
BadgeConfig21+
Describes the badge configuration.
Atomic service API: This API can be used in atomic services since API version 21.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| badgeType | BadgeType | No | Yes | Badge type. |
| uris | Array<string> | No | Yes | URIs of the assets for the badge. |
ClickResult23+
Sets whether the asset with the specified URI is selected.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| uri | string | No | No | URI of the media asset. |
| isSelected | boolean | No | No | Sets whether the specified media asset is selected. The value true indicates that the asset is selected, and false indicates the opposite. |
PreselectedInfo21+
Describes the information about the preselected files and their corresponding PhotoPickerComponent index.
Atomic service API: This API can be used in atomic services since API version 21.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| uri | string | No | No | URI of the preselected media file. |
| preselectablePickerIndex | number | No | Yes | Index of the PhotoPickerComponent that can be used in automatic selection. The default value is -1, which allows automatic selection in any PhotoPickerComponent. |
UpdatablePickerConfigs22+
Describes the updatable attributes of the PhotoPickerComponent. These attributes are a subset of PickerOptions.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| mimeType | photoAccessHelper.PhotoViewMIMETypes | No | Yes | MIME types. If this parameter is not specified, IMAGE_VIDEO_TYPE is used by default. Atomic service API: This API can be used in atomic services since API version 22. |
| mimeTypeFilter | photoAccessHelper.MimeTypeFilter | No | Yes | Configuration for file type filtering. Multiple types can be specified. - When this parameter is set, the mimeType configuration automatically becomes invalid. - When this parameter is set, only media files of the configured filter type are displayed. You are advised to notify users that only images or videos of the specified type can be selected. Atomic service API: This API can be used in atomic services since API version 22. |
| maxSelectNumber | number | No | Yes | Maximum number of media files that can be selected. The maximum value is 500, and the default value is 50. Atomic service API: This API can be used in atomic services since API version 22. |
| maxPhotoSelectNumber | number | No | Yes | Maximum number of images that can be selected (unit: number). The maximum value is 500, which is limited by MaxSelected. The default value is 500. Atomic service API: This API can be used in atomic services since API version 22. |
| maxVideoSelectNumber | number | No | Yes | Maximum number of videos that can be selected (unit: number). The maximum value is 500, and it is restricted by the maximum number of media files that can be selected in the system. The default value is 500. Atomic service API: This API can be used in atomic services since API version 22. |
| selectMode | SelectMode | No | Yes | Picker selection mode. SINGLE_SELECT or MULTI_SELECT. The default value is MULTI_SELECT. Atomic service API: This API can be used in atomic services since API version 22. |
| singleSelectionMode | photoAccessHelper.SingleSelectionMode | No | Yes | Single selection mode. The default value is SingleSelectionMode.BROWSER_MODE. Atomic service API: This API can be used in atomic services since API version 22. |
| isRepeatSelectSupported | boolean | No | Yes | Whether a single image can be repeatedly selected. true if supported, false otherwise. The default value is false. Atomic service API: This API can be used in atomic services since API version 22. |
| preselectedUris | Array<string> | No | Yes | URIs of the selected images. Atomic service API: This API can be used in atomic services since API version 22. |
| checkBoxColor | string | No | Yes | Background color of the check box. The value is an 8-digit hexadecimal color code. Atomic service API: This API can be used in atomic services since API version 22. |
| backgroundColor | string | No | Yes | Background color of the Picker grid page. The value is an 8-digit hexadecimal color code. Atomic service API: This API can be used in atomic services since API version 22. |
| checkboxTextColor | string | No | Yes | Text color in the check box. The value is an 8-digit hexadecimal color code. Atomic service API: This API can be used in atomic services since API version 22. |
| photoBrowserBackgroundColorMode | PickerColorMode | No | Yes | Background color of the photo browser page. The options are AUTO, LIGHT, and DARK. The default value is AUTO. Atomic service API: This API can be used in atomic services since API version 22. |
| uiComponentColorMode | PickerColorMode | No | Yes | Color mode of the Picker UI component. Dark/Light color mode (excluding the background color) of other components on the Picker grid page, including the search box, camera entry, safety tips for using Gallery, and recommendation bubble. This attribute is usually used together with backgroundColor. The default value is PickerColorMode.AUTO, which follows the system's dark/light color mode. When setting this attribute, avoid using PickerColorMode.LIGHT with a dark background color, as it may make components or text hard to see. Avoid using PickerColorMode.DARK with a light background color for the same reason. Atomic service API: This API can be used in atomic services since API version 22. |
| isSlidingSupported23+ | boolean | No | Yes | Whether scrolling in the PhotoPickerComponent is enabled. The value true means that scrolling is not blocked and the component responds to user scroll gestures. The value false means that scrolling is blocked and the component does not respond to user scroll gestures. The default value is true. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 23. |
| edgeEffect23+ | EdgeEffect | No | Yes | Scrolling effect when the Picker grid page reaches the edge. The default value is EdgeEffect.Spring. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 23. |
| appAlbumFilters23+ | Array<string> | No | Yes | Used to display only the album content corresponding to the specified bundle name. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 23. |
| autoPlayScenes23+ | Array<photoAccessHelper.AutoPlayScene> | No | Yes | Playback mode of the moving photo. The maximum array length is 2. If this limit is exceeded, the first two elements are used, and the extra ones are automatically ignored. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 23. |
| backgroundOpacity24+ | number | No | Yes | Background opacity of the picker. The value range is [0, 1]. 0 indicates completely transparent, and 1 indicates completely opaque. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 24. |
PickerError23+
Describes the function name, error code, and message of the error returned when an error occurs during the use of the PhotoPickerComponent component.
Model restriction: This API can be used only in the stage model.
Atomic service API: This API can be used in atomic services since API version 23.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Type | Read-Only | Optional | Description |
|---|---|---|---|---|
| functionName | string | No | No | Function name of the error. |
| errorCode | number | No | No | Error code. |
| message | string | No | No | Error message. |
DataType
Enumerates the types of data sent from PickerController to the PhotoPickerComponent.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Value | Description |
|---|---|---|
| SET_SELECTED_URIS | 1 | Sends a list of selected items to instruct the PhotoPickerComponent to refresh the selection status. A string array needs to be passed in. For example, after an image is deleted from an application's page, the application calls setData() to notify the PhotoPickerComponent of the remaining selected items. Then, the PhotoPickerComponent refreshes the check box status. Atomic service API: This API can be used in atomic services since API version 12. |
| SET_ALBUM_URI | 2 | Sends the selected album to instruct the PhotoPickerComponent to refresh the album data. A string array needs to be passed in. For example, after an album is selected from an application's page, the application calls setData to notify the PhotoPickerComponent of the URI of the selected album. Then, the PhotoPickerComponent refreshes the album data. Atomic service API: This API can be used in atomic services since API version 12. |
| SET_SELECTED_INFO21+ | 3 | Sends the URI of the selected file and the index of the selected PhotoPickerComponent. If the index of a PhotoPickerComponent matches the one provided in the parameter, the selected file is automatically highlighted in that PhotoPickerComponent. Atomic service API: This API can be used in atomic services since API version 21. |
| SET_BADGE_CONFIGS21+ | 4 | Sends the badge configurations, which are of the badgeConfig type and include a list of data with badge types and corresponding file URIs. Once configured, the badge of the configured type is displayed in the specified file. Atomic service API: This API can be used in atomic services since API version 21. |
| SET_ITEM_CLICK_RESULT23+ | 5 | Result of the click, which is of the ClickResult type. Model restriction: This API can be used only in the stage model. Atomic service API: This API can be used in atomic services since API version 23. |
ItemType
Enumerates the types of the item clicked.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Value | Description |
|---|---|---|
| THUMBNAIL | 0 | Image or video (thumbnail). |
| CAMERA | 1 | Camera item. |
ClickType
Enumerates the click operation types.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Value | Description |
|---|---|---|
| SELECTED | 0 | Select (select an image or click a camera item). |
| DESELECTED | 1 | Deselect (deselect an image). |
PickerOrientation
Enumerates the sliding preview directions of the Picker grid page.
This capability can be configured since API version 20. If this capability is set since API version 12 to 19, the setting does not take effect and the default direction (vertical) is used.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Value | Description |
|---|---|---|
| VERTICAL | 0 | Vertical direction. |
| HORIZONTAL | 1 | Horizontal direction. |
SelectMode
Enumerates the selection modes.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Value | Description |
|---|---|---|
| SINGLE_SELECT | 0 | Select a single option. |
| MULTI_SELECT | 1 | Select multiple options. |
PickerColorMode
Enumerates the Picker color modes.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Value | Description |
|---|---|---|
| AUTO | 0 | Same with the system. |
| LIGHT | 1 | Light mode. |
| DARK | 2 | Dark mode. |
ReminderMode
Enumerates the types of the reminder when the number of selected items reaches the maximum.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Value | Description |
|---|---|---|
| NONE | 0 | No reminder. |
| TOAST | 1 | Toast message. |
| MASK | 2 | Grayed-out hint. |
MaxCountType
Enumerates the types of the maximum count.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Value | Description |
|---|---|---|
| TOTAL_MAX_COUNT | 0 | Total number of media assets (images and videos) that can be selected. |
| PHOTO_MAX_COUNT | 1 | Total number of images that can be selected. The value cannot be greater than Total_MAX_Count. |
| VIDEO_MAX_COUNT | 2 | Total number of videos that can be selected. The value cannot be greater than Total_MAX_Count. |
PhotoBrowserRange
Enumerates the view range on the photo browser page.
Atomic service API: This API can be used in atomic services since API version 12.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Value | Description |
|---|---|---|
| ALL | 0 | View all images and videos. |
| SELECTED_ONLY | 1 | View selected images and videos only. |
PhotoBrowserUIElement13+
Represents other UI elements except the image preview component on the photo browser page.
Atomic service API: This API can be used in atomic services since API version 13.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Value | Description |
|---|---|---|
| CHECKBOX | 0 | Check box on the photo browser page. |
| BACK_BUTTON | 1 | Back button on the photo browser page. |
SaveMode15+
Enumerates the modes for saving images or videos.
Atomic service API: This API can be used in atomic services since API version 15.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Value | Description |
|---|---|---|
| SAVE_AS | 0 | Saves the image or video as a new one. |
| OVERWRITE | 1 | Replaces the original image or video. After the replacements, you can roll back the saved content in Gallery to restore the original image or video. |
BadgeType21+
Enumerates the badge types.
Atomic service API: This API can be used in atomic services since API version 21.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Value | Description |
|---|---|---|
| BADGE_UPLOADED | 0 | Uploaded. |
VideoPlayerState14+
Enumerates the video playback states.
Atomic service API: This API can be used in atomic services since API version 14.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Value | Description |
|---|---|---|
| PLAYING | 0 | The video is being played. |
| PAUSED | 1 | Video playback is paused. |
| STOPPED | 2 | Video playback is stopped. |
| SEEK_START | 3 | Started dragging the progress bar. |
| SEEK_FINISH | 4 | Finished dragging the progress bar. |
ItemDisplayRatio20+
Enumerates the aspect ratios for grid display in single-line display mode.
Atomic service API: This API can be used in atomic services since API version 20.
System capability: SystemCapability.FileManagement.PhotoAccessHelper.Core
| Name | Value | Description |
|---|---|---|
| SQUARE_RATIO | 0 | 1:1 ratio. |
| ORIGINAL_SIZE_RATIO | 1 | Original image aspect ratio. |
Example 1: Using the PhotoPickerComponent Component
// xxx.ets
// In versions earlier than API version 23, you need to use the 'import { api1, api2,... } from @ohos.file.PhotoPickerComponent' import mode.
import {
PhotoPickerComponent,
PickerController,
PickerOptions,
DataType,
BaseItemInfo,
ItemInfo,
PhotoBrowserInfo,
ItemType,
ClickType,
MaxCountType,
PhotoBrowserRange,
PhotoBrowserUIElement,
ItemsDeletedCallback,
ExceedMaxSelectedCallback,
CurrentAlbumDeletedCallback,
videoPlayStateChangedCallback,
VideoPlayerState,
photoAccessHelper
} from '@kit.MediaLibraryKit';
import { dataSharePredicates } from '@kit.ArkData';
import { common } from '@kit.AbilityKit';
@Entry
@Component
struct PickerDemo {
pickerOptions: PickerOptions = new PickerOptions();
@State pickerController: PickerController = new PickerController();
@State selectUris: string[] = [];
@State currentUri: string = '';
@State isBrowserShow: boolean = false;
private selectedItemsDeletedCallback: ItemsDeletedCallback =
(baseItemInfos: Array<BaseItemInfo>) => this.onSelectedItemsDeleted(baseItemInfos);
private exceedMaxSelectedCallback: ExceedMaxSelectedCallback =
(exceedMaxCountType: MaxCountType) => this.onExceedMaxSelected(exceedMaxCountType);
private currentAlbumDeletedCallback: CurrentAlbumDeletedCallback = () => this.onCurrentAlbumDeleted();
private videoPlayStateChangedCallback: videoPlayStateChangedCallback =
(state: VideoPlayerState) => this.videoPlayStateChanged(state);
private thumbnail: PixelMap[] = [];
private assets: photoAccessHelper.PhotoAsset[] = [];
aboutToAppear() {
this.pickerOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE;
this.pickerOptions.maxSelectNumber = 5;
this.pickerOptions.isSearchSupported = false;
this.pickerOptions.isPhotoTakingSupported = false;
this.pickerOptions.photoBrowserCheckboxPosition = [0.5, 0.5];
// Other attributes
}
private onSelect(uri: string): void {
// Add
if (uri) {
this.selectUris.push(uri);
}
}
private onDeselect(uri: string): void {
// Remove
if (uri) {
this.selectUris = this.selectUris.filter((item: string) => {
return item != uri;
})
}
}
private onItemClicked(itemInfo: ItemInfo, clickType: ClickType): boolean {
if (!itemInfo) {
return false;
}
let type: ItemType | undefined = itemInfo.itemType;
let uri: string | undefined = itemInfo.uri;
if (type === ItemType.CAMERA) {
// Click a camera item.
return true; // If true is returned, the system camera is started. If false is returned, the app processes its services.
} else {
if (clickType === ClickType.SELECTED) {
// The application performs its own service logic (not time-consuming operations, such as opening a large file using openSync).
if (uri) {
this.selectUris.push(uri);
this.pickerOptions.preselectedUris = [...this.selectUris];
}
return true; // If true is returned, the check box is selected. Otherwise, the check box is not selected.
} else {
if (uri) {
this.selectUris = this.selectUris.filter((item: string) => {
return item != uri;
});
this.pickerOptions.preselectedUris = [...this.selectUris];
}
}
return true;
}
}
private onEnterPhotoBrowser(photoBrowserInfo: PhotoBrowserInfo): boolean {
// Callback to be invoked when the photo browser page is displayed.
this.isBrowserShow = true;
return true;
}
private onExitPhotoBrowser(photoBrowserInfo: PhotoBrowserInfo): boolean {
// Callback to be invoked when the photo browser page is closed.
this.isBrowserShow = false;
return true;
}
private onPickerControllerReady(): void {
// After the callback is called, pickerController APIs can be called to send data to Picker. Before the callback is called, pickerController APIs do not take effect.
let elements: number[] = [PhotoBrowserUIElement.BACK_BUTTON];
this.pickerController.setPhotoBrowserUIElementVisibility(elements, false); // Hide the Back button on the photo browser page.
}
private onPhotoBrowserChanged(browserItemInfo: BaseItemInfo): boolean {
// Callback to be invoked when the photo browser is swiped left or right.
this.currentUri = browserItemInfo.uri ?? '';
return true;
}
private onSelectedItemsDeleted(baseItemInfos: Array<BaseItemInfo>): void {
// Callback to be invoked when the selected image is deleted.
}
private onExceedMaxSelected(exceedMaxCountType: MaxCountType): void {
// Callback to be invoked when the number of selected items exceeds the maximum.
}
private onCurrentAlbumDeleted(): void {
// Callback to be invoked when the current album is deleted.
}
private videoPlayStateChanged(state: VideoPlayerState): void {
// Called when the video playback state changes.
}
build() {
Flex({
direction: FlexDirection.Column,
justifyContent: FlexAlign.Center,
alignItems: ItemAlign.Center
}) {
Column() {
if (this.isBrowserShow) {
// Back button of the application on the photo browser page.
Row() {
Button("Exit photo browser page").width('33%').height('8%').onClick(() => {
this.pickerController.exitPhotoBrowser();
})
}.margin({ bottom: 20 })
}
PhotoPickerComponent({
pickerOptions: this.pickerOptions,
onSelect: (uri: string): void => this.onSelect(uri),
onDeselect: (uri: string): void => this.onDeselect(uri),
onItemClicked: (itemInfo: ItemInfo, clickType: ClickType): boolean => this.onItemClicked(itemInfo,
clickType), // This API can replace the preceding two APIs.
onEnterPhotoBrowser: (photoBrowserInfo: PhotoBrowserInfo): boolean => this.onEnterPhotoBrowser(photoBrowserInfo),
onExitPhotoBrowser: (photoBrowserInfo: PhotoBrowserInfo): boolean => this.onExitPhotoBrowser(photoBrowserInfo),
onPickerControllerReady: (): void => this.onPickerControllerReady(),
onPhotoBrowserChanged: (browserItemInfo: BaseItemInfo): boolean => this.onPhotoBrowserChanged(browserItemInfo),
onSelectedItemsDeleted: this.selectedItemsDeletedCallback,
onExceedMaxSelected: this.exceedMaxSelectedCallback,
onCurrentAlbumDeleted: this.currentAlbumDeletedCallback,
onVideoPlayStateChanged: this.videoPlayStateChangedCallback,
pickerController: this.pickerController,
}).height('60%').width('100%')
// Simulate the selection bar at the bottom of the application.
if (this.isBrowserShow) {
Row() {
ForEach(this.assets, async (asset: photoAccessHelper.PhotoAsset, index) => {
if (asset.uri === this.currentUri) {
Image(this.thumbnail[index])
.height('10%')
.width('10%')
.onClick(() => {
})
.borderWidth(1)
.borderColor('red')
} else {
Image(this.thumbnail[index]).height('10%').width('10%').onClick(() => {
this.pickerController.setData(DataType.SET_SELECTED_URIS, this.selectUris);
this.pickerController.setPhotoBrowserItem(asset.uri, PhotoBrowserRange.ALL);
})
}
}, (uri: string) => JSON.stringify(uri))
}
} else {
Button('Preview').width('33%').height('5%').onClick(async () => {
if (this.selectUris.length > 0) {
this.thumbnail = [];
this.assets = [];
for (let selectUri of this.selectUris) {
let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
predicates.equalTo(photoAccessHelper.PhotoKeys.URI, selectUri);
let fetchOptions: photoAccessHelper.FetchOptions = {
fetchColumns: [],
predicates: predicates
};
let context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext;
let photoHelper = photoAccessHelper.getPhotoAccessHelper(context);
let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> =
await photoHelper.getAssets(fetchOptions);
let asset = await fetchResult.getFirstObject()
this.assets.push(asset);
this.thumbnail.push(await asset.getThumbnail())
}
this.pickerController.setPhotoBrowserItem(this.selectUris[0], PhotoBrowserRange.SELECTED_ONLY);
}
})
}
}
}
}
}
Example 2: Using PhotoPickerComponent to Implement the Drawer Component Effect
Since API version 23, you can use the isSlidingSupported callback of PickerOptions and the onScrollStopAtStart and onScrollStopAtEnd callbacks of PhotoPickerComponent to implement the drawer effect.
// xxx.ets
import { display } from '@kit.ArkUI';
import { PhotoPickerComponent, PickerController, PickerOptions } from '@kit.MediaLibraryKit';
const enum DrawerState {
// Expanded state.
Expanding,
// Collapsed state.
Collapsing,
// Sliding state.
Sliding
}
@Entry
@Component
struct Drawer {
@State pickerController: PickerController = new PickerController();
private pickerOptions: PickerOptions = new PickerOptions();
// Screen height, in vp.
@State screenHeight: number = 0;
// Drawer height, in vp.
@State drawerHeight: number = 0;
// Drawer offset, in vp.
@State offsetY: number = 0;
// Whether the drawer is expanded.
@State isExpanded: boolean = false;
// Start position of dragging, in vp.
private startY: number = 0;
// Current dragging offset, in vp.
private currentOffset: number = 0;
// Percentage of the custom drawer height to the entire screen.
private drawerRatio: number = 0.8;
// Percentage of the custom drawer to be hidden during initialization.
private hideRatio: number = 0.8;
// Initialize the drawer to the collapsed state.
private drawerState: DrawerState = DrawerState.Collapsing;
// Gesture response threshold, which is used to determine whether the gesture is downward.
private pullingDownThreshold: number = -5;
aboutToAppear(): void {
// Obtain the display height.
this.screenHeight = px2vp(display.getDefaultDisplaySync().height);
// Obtain the drawer height. In this example, the height is 0.8 times the display height, which can be customized.
this.drawerHeight = this.screenHeight * this.drawerRatio;
// Initially, the drawer is at the bottom and fully hidden. In this example, 80% of the drawer height is hidden.
this.offsetY = this.drawerHeight * this.hideRatio;
// The Picker does not support sliding during initialization.
this.pickerOptions.isSlidingSupported = false;
// No edge effect.
this.pickerOptions.edgeEffect = EdgeEffect.None;
// The search box is not displayed.
this.pickerOptions.isSearchSupported = false;
}
private scrollStopAtStart() {
// Change the state to expanded and disable the grid sliding.
this.drawerState = DrawerState.Expanding;
this.pickerController.updatePickerOptions({
isSlidingSupported: false
})
}
private toggleDrawer() {
if (this.isExpanded) {
this.hideDrawer();
} else {
this.showDrawer();
}
}
private hideDrawer() {
animateTo({
duration: 300,
curve: Curve.EaseOut,
onFinish: () => {
this.isExpanded = false;
}
}, () => {
this.drawerState = DrawerState.Collapsing;
this.offsetY = this.drawerHeight * 0.8;
})
}
private showDrawer() {
animateTo({
duration: 300,
curve: Curve.EaseOut,
onFinish: () => {
this.isExpanded = true;
}
}, () => {
this.drawerState = DrawerState.Expanding;
this.offsetY = 0;
})
}
build() {
RelativeContainer() {
// Main content area.
Column() {
Text('Main page content')
.fontSize(24)
.fontWeight(FontWeight.Bold)
.margin({ bottom: 20 })
Text('This is a bottom drawer effect implemented using RelativeContainer.')
.fontSize(16)
.fontColor('#666')
.margin({ bottom: 30 })
.textAlign(TextAlign.Center)
.width('80%')
Button(this.isExpanded? 'Collapse drawer' : 'Expand drawer')
.onClick(() => {
this.toggleDrawer();
})
}
.width('100%')
.padding(20)
.alignItems(HorizontalAlign.Center)
.backgroundColor('#f5f5f5')
.borderRadius(10)
.alignRules({
top: { anchor: '__container__', align: VerticalAlign.Top },
left: { anchor: '__container__', align: HorizontalAlign.Start },
right: { anchor: '__container__', align: HorizontalAlign.End },
})
.height('100%')
if (this.isExpanded) {
Column()
.width('100%')
.height('100%')
.backgroundColor('#80000000')
.alignRules({
top: { anchor: '__container__', align: VerticalAlign.Top },
left: { anchor: '__container__', align: HorizontalAlign.Start },
right: { anchor: '__container__', align: HorizontalAlign.End },
bottom: { anchor: '__container__', align: VerticalAlign.Bottom },
})
.onClick(() => {
this.hideDrawer();
})
}
Column() {
Row()
.width(50)
.height(5)
.backgroundColor('#CCC')
.borderRadius(3)
.margin({ top: 12, bottom: 8 })
Text ('Drawer menu')
.fontSize(18)
.fontWeight(FontWeight.Medium)
.margin({ bottom: 10 })
Divider()
.width('90%')
.margin({ bottom: 10 })
PhotoPickerComponent({
pickerOptions: this.pickerOptions,
pickerController: this.pickerController,
onScrollStopAtStart: this.scrollStopAtStart
})
.layoutWeight(1)
.width('100%')
}
.width('100%')
.height(this.drawerHeight)
.backgroundColor(Color.White)
.borderRadius({ topLeft: 20, topRight: 20 })
.shadow({ radius: 10, color: '#33000000' })
.alignRules({
left: { anchor: '__container__', align: HorizontalAlign.Start },
right: { anchor: '__container__', align: HorizontalAlign.End },
bottom: { anchor: '__container__', align: VerticalAlign.Bottom },
})
.translate({ y: this.offsetY })
.gesture(
PanGesture({ direction: PanDirection.Vertical })
// Record the position where the drawer starts to be dragged.
.onActionStart((event: GestureEvent) => {
this.startY = event.fingerList[0].globalY || 0;
this.currentOffset = this.offsetY;
})
.onActionUpdate((event: GestureEvent) => {
// If the drawer is in the Picker sliding state, do not change the drawer height and return directly.
if (this.drawerState === DrawerState.Sliding) {
return;
}
// If the drawer is expanded or collapsed, use gestures to further change the drawer state.
// Calculate the moving distance.
const deltaY = event.fingerList[0].globalY - this.startY || 0;
// When the drawer is expanded and the user swipes down, enable the grid sliding function and switch the drawer state to the sliding state.
if (this.drawerState === DrawerState.Expanding && deltaY < this.pullingDownThreshold) {
this.pickerController.updatePickerOptions({
isSlidingSupported: true
})
this.drawerState = DrawerState.Sliding
}
let newOffset = this.currentOffset + deltaY;
if (newOffset < 0) {
newOffset = 0;
}
this.offsetY = newOffset;
})
.onActionEnd(()=>{
// When the gesture ends, the drawer is automatically expanded or collapsed based on the position.
if (this.offsetY > this.drawerHeight / 2) {
// If the sliding distance exceeds half of the drawer height, the drawer is collapsed.
this.hideDrawer();
} else {
// If the sliding distance is less than half of the drawer height, the drawer is expanded.
this.showDrawer();
}
})
)
}
.width('100%')
.height('100%')
.backgroundColor('#E0E0E0')
}
}