• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.file.PhotoPickerComponent (PhotoPickerComponent)
2<!--Kit: Media Library Kit-->
3<!--Subsystem: Multimedia-->
4<!--Owner: @xuchangda-->
5<!--SE: @guxinggang-->
6<!--TSE: @wangbeibei-->
7
8You 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.
9
10Note 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.
11
12Once embedded, users can directly select images or videos within the **PhotoPickerComponent**.
13
14> **NOTE**
15>
16> This component is supported since API version 12. Updates will be marked with a superscript to indicate their earliest API version.
17
18## Modules to Import
19
20```ts
21import {
22  PhotoPickerComponent, PickerController, PickerOptions,
23  DataType, BaseItemInfo, ItemInfo, PhotoBrowserInfo, ItemType, ClickType,
24  MaxCountType, PhotoBrowserRange, PhotoBrowserUIElement,
25  ItemsDeletedCallback, ExceedMaxSelectedCallback, CurrentAlbumDeletedCallback
26} from '@ohos.file.PhotoPickerComponent';
27```
28
29## Properties
30
31The [universal properties](../apis-arkui/arkui-ts/ts-component-general-attributes.md) are supported.
32
33## PhotoPickerComponent
34
35PhotoPickerComponent({
36  pickerOptions?: PickerOptions,
37  onSelect?: (uri: string) => void,
38  onDeselect?: (uri: string) => void,
39  onItemClicked?: (itemInfo: ItemInfo, clickType: ClickType) => boolean,
40  onEnterPhotoBrowser?: (photoBrowserInfo: PhotoBrowserInfo) => boolean,
41  onExitPhotoBrowser?: (photoBrowserInfo: PhotoBrowserInfo) => boolean,
42  onPickerControllerReady?: () => void,
43  onPhotoBrowserChanged?: (browserItemInfo: BaseItemInfo) => boolean,
44  onSelectedItemsDeleted?: ItemsDeletedCallback,
45  onExceedMaxSelected?: ExceedMaxSelectedCallback,
46  onCurrentAlbumDeleted?: CurrentAlbumDeletedCallback,
47  onVideoPlayStateChanged?: videoPlayStateChangedCallback,
48  pickerController: PickerController
49})
50
51Allows the application to access images or videos in the user directory without any permission.
52
53> **NOTE**
54>
55> 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.
56
57**Decorator**: @Component
58
59**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
60
61**Parameters**
62
63| Name                     | Type                                                                              | Mandatory | Decorator Type     | Description                                                                                                                                                                                                                                                                                                                                                           |
64|-------------------------|----------------------------------------------------------------------------------|-----|------------|-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------|
65| pickerOptions           | [PickerOptions](#pickeroptions)                                                  | No  | - | Picker configuration parameters.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                                                                                                                                                                                                                                                                                                                                    |
66| 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.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                                                                                                                                                                                                                                                                                                           |
67| 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.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                                                                                                                                                                                                                                                                                                     |
68| onItemClicked           | (itemInfo: [ItemInfo](#iteminfo), clickType: [ClickType](#clicktype)) => boolean | No  | - | Callback to be invoked when an item in a **PhotoPickerComponent** is clicked.<br>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.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                                                                                                                                                                                                                           |
69| onEnterPhotoBrowser     | (photoBrowserInfo: [PhotoBrowserInfo](#photobrowserinfo)) => boolean             | No  | - | Callback to be invoked when the photo browser page is displayed. The callback returns photo browser information to the application.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                                                                                                                                                                                                                                                                                                                    |
70| onExitPhotoBrowser      | (photoBrowserInfo: [PhotoBrowserInfo](#photobrowserinfo)) => boolean             | No  | - | Callback to be invoked when the photo browser page exits. The callback returns photo browser information to the application.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                                                                                                                                                                                                                                                                                                                      |
71| onPickerControllerReady | () => void                                                                       | No  | - | Callback to be invoked when **pickerController** is available.<br>The **PickerController** APIs can be called only after this callback is invoked.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                                                                                                                                                                                                                                                                              |
72| onPhotoBrowserChanged   | (browserItemInfo: [BaseItemInfo](#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.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                                                                                                                                                                                                                                                                                                                    |
73| onSelectedItemsDeleted<sup>13+</sup>  | [ItemsDeletedCallback](#itemsdeletedcallback13)                                  | No  | - | Callback to be invoked when the selected items are deleted. This callback returns information about the deleted items to the application.<br>**Atomic service API**: This API can be used in atomic services since API version 13.                                                                                                                                                                                                                                                                                                                             |
74| onExceedMaxSelected<sup>13+</sup>     | [ExceedMaxSelectedCallback](#exceedmaxselectedcallback13)                          | 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).<br>- 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](#maxcounttype).PHOTO_MAX_COUNT.<br>- 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](#maxcounttype).VIDEO_MAX_COUNT.<br>- If the number of selected media assets reaches the maximum count of selected items, **exceedMaxCountType** in the callback is [MaxCountType](#maxcounttype).TOTAL_MAX_COUNT.<br>**Atomic service API**: This API can be used in atomic services since API version 13.|
75| onCurrentAlbumDeleted<sup>13+</sup>   | [CurrentAlbumDeletedCallback](#currentalbumdeletedcallback13)                    | No  | - | Callback to be invoked when the current album is deleted.<br>The album is specified by **currentAlbumUri** in pickerController.[setData](#setdata)([DataType](#datatype).SET_ALBUM_URI, currentAlbumUri).<br>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](#setdata)([DataType](#datatype).SET_ALBUM_URI, '') with an empty string.<br>**Atomic service API**: This API can be used in atomic services since API version 13.                                 |
76| onVideoPlayStateChanged<sup>14+</sup>   | [videoPlayStateChangedCallback](#videoplaystatechangedcallback14)                    | No  | - | Callback to be invoked when the video playback state on a photo browser page changes.<br>**Atomic service API**: This API can be used in atomic services since API version 14.                                 |
77| pickerController        | [PickerController](#pickercontroller)                                            | No  | @ObjectLink | Instance used to send data to the **PhotoPickerComponent**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                                                                                                                                                                                                                                                                                                            |
78
79## PickerOptions
80
81Describes the configuration of a Picker. It inherits from [BaseSelectOptions](arkts-apis-photoAccessHelper-class.md#baseselectoptions12).
82
83
84
85**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
86
87| Name                             | Type                                     | Mandatory | Description                                                                      |
88|---------------------------------|-----------------------------------------|-----|--------------------------------------------------------------------------|
89| checkBoxColor                   | string                                  | No  | Background color of the check box. The value is an 8-digit hexadecimal color code.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                                  |
90| backgroundColor                 | string                                  | No  | Background color of the Picker grid page. The value is an 8-digit hexadecimal color code.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                            |
91| isRepeatSelectSupported         | boolean                                 | No  | Whether to support repeat selection of a single image. The value **true** means that a single image can be repeatedly selected. The default value is **false**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                                  |
92| checkboxTextColor               | string                                  | No  | Text color in the check box. The value is an 8-digit hexadecimal color code. (This capability is not supported currently.)<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                       |
93| photoBrowserBackgroundColorMode | [PickerColorMode](#pickercolormode)     | No  | Background color of the photo browser page. The options are **AUTO**, **LIGHT**, and **DARK**. The default value is **AUTO**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                       |
94| maxSelectedReminderMode         | [ReminderMode](#remindermode)           | No  | Mode of the reminder when the number of selected items reaches the maximum. The options are **NONE**, **TOAST**, and **MASK**. The default value **TOAST**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                        |
95| orientation                     | [PickerOrientation](#pickerorientation) | No  | Sliding preview direction of the grid page. The options are **HORIZONTAL** and **VERTICAL**. The default value is **VERTICAL**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                |
96| selectMode                      | [SelectMode](#selectmode)               | No  | Select mode, which can be **SINGLE_SELECT** or **MULTI_SELECT**. The default value is **MULTI_SELECT**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                                     |
97| maxPhotoSelectNumber            | number                                  | No  | Maximum number of images that can be selected. The maximum value is **500**, which is limited by **MaxSelected**. The default value is **500**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                          |
98| maxVideoSelectNumber            | number                                  | No  | Maximum number of videos that can be selected. The maximum value is **500**, which is limited by **MaxSelected**. The default value is **500**.<br>**Atomic service API**: This API can be used in atomic services since API version 12.                                          |
99| isSlidingSelectionSupported<sup>13+</sup>     | boolean                                 | No  | Whether sliding selection (selecting multiple items by sliding finger across the screen) is supported. The value **true** means that sliding selection is supported. By default, it is not supported. This parameter is not available for repeat selection.<br>**Atomic service API**: This API can be used in atomic services since API version 13.                                           |
100| photoBrowserCheckboxPosition<sup>13+</sup>    | [number, number]                        | No  | 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].<br>**Atomic service API**: This API can be used in atomic services since API version 13.|
101| gridMargin<sup>14+</sup>        | [Margin](../../reference/apis-arkui/arkui-ts/ts-universal-attributes-size.md#margin)                        | No  | Margin of the component on a grid page.<br>**Atomic service API**: This API can be used in atomic services since API version 14.|
102| photoBrowserMargin<sup>14+</sup>    | [Margin](../../reference/apis-arkui/arkui-ts/ts-universal-attributes-size.md#margin)                        | No  | Margin of the component on a photo browser page.<br>**Atomic service API**: This API can be used in atomic services since API version 14.|
103| singleLineConfig<sup>20+</sup>             | [SingleLineConfig](#singlelineconfig)                                                | No  | 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.<br>**Atomic service API**: This API can be used in atomic services since API version 20.     |
104| uiComponentColorMode<sup>20+</sup>             | [PickerColorMode](#pickercolormode)                                                | No  | 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 property is usually used together with **backgroundColor**. The default value is **PickerColorMode.AUTO**, which follows the system's dark/light color mode.<br>When setting this property, 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.<br>**Atomic service API**: This API can be used in atomic services since API version 20. |
105| gridStartOffset<sup>20+</sup>    | number                              | No  | Space between the top of the component and the first row of the grid thumbnail. The default value is **0**, in vp.<br>**Atomic service API**: This API can be used in atomic services since API version 20.|
106| gridEndOffset<sup>20+</sup>    | number                              | No  | Space between the bottom of the component and the last row of the grid thumbnail. The default value is **0**, in vp.<br>**Atomic service API**: This API can be used in atomic services since API version 20.|
107
108## ItemsDeletedCallback<sup>13+</sup>
109
110type ItemsDeletedCallback = (baseItemInfos: Array&lt;BaseItemInfo&gt;) => void
111
112Called when the selected items are deleted.
113
114**Atomic service API**: This API can be used in atomic services since API version 13.
115
116**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
117
118**Parameters**
119
120| Name| Type                                        | Mandatory| Description      |
121| -------- |--------------------------------------------| -------- |----------|
122| baseItemInfos | Array&lt;[BaseItemInfo](#baseiteminfo)&gt; | Yes| Basic information about the selected items.|
123
124## ExceedMaxSelectedCallback<sup>13+</sup>
125
126type ExceedMaxSelectedCallback = (exceedMaxCountType: MaxCountType) => void
127
128Called when items are selected after the maximum count has been reached.
129
130**Atomic service API**: This API can be used in atomic services since API version 13.
131
132**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
133
134**Parameters**
135
136| Name| Type                           | Mandatory| Description                                          |
137| -------- |-------------------------------| -------- |----------------------------------------------|
138| exceedMaxCountType | [MaxCountType](#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.|
139
140## CurrentAlbumDeletedCallback<sup>13+</sup>
141
142type CurrentAlbumDeletedCallback = () => void
143
144Called when the current album is deleted.
145
146**Atomic service API**: This API can be used in atomic services since API version 13.
147
148**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
149
150## videoPlayStateChangedCallback<sup>14+</sup>
151
152type videoPlayStateChangedCallback = (state: VideoPlayerState) => void
153
154Callback to be invoked when the video playback state on a photo browser page changes.
155
156**Atomic service API**: This API can be used in atomic services since API version 14.
157
158**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
159
160## PickerController
161
162Defines an instance used to send data to the **PhotoPickerComponent**.
163
164**Decorator Type**: @Observed
165
166**Atomic service API**: This API can be used in atomic services since API version 12.
167
168**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
169
170### setData
171
172setData(dataType: DataType, data: Object): void
173
174Sends data of the specified type to **PhotoPickerComponent**.
175
176**Atomic service API**: This API can be used in atomic services since API version 12.
177
178**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
179
180**Parameters**
181
182|  Name       | Type                                   | Mandatory | Description |
183| ------------------------- | ------------------ | ----- | --------------- |
184| dataType | [DataType](#datatype) | Yes| Type of the data to send.|
185| data | Object | Yes| Data to send.|
186
187### setMaxSelected
188
189setMaxSelected(maxSelected: MaxSelected): void
190
191Sets the maximum number of images, videos, or images and videos that can be selected on a real-time basis.
192
193**Atomic service API**: This API can be used in atomic services since API version 12.
194
195**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
196
197**Parameters**
198
199|  Name       | Type                                   | Mandatory | Description    |
200| ------------------------- | ------------------ | ----- | --------------- |
201| maxSelected | [MaxSelected](#maxselected) | Yes| Maximum number of media assets that can be selected at a time.|
202
203### setPhotoBrowserItem
204
205setPhotoBrowserItem(uri: string, photoBrowserRange?: PhotoBrowserRange): void
206
207Switches from the **PhotoPickerComponent** to the photo browser page or from the photo browser page to the image to be viewed.
208
209**Atomic service API**: This API can be used in atomic services since API version 12.
210
211**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
212
213**Parameters**
214
215|  Name       | Type                                   | Mandatory | Description |
216| ------------------------- | ------------------ | ----- | --------------- |
217| uri | string | Yes| URI of the image to view. Only the images selected by the user are supported.|
218| photoBrowserRange | [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.|
219
220### exitPhotoBrowser<sup>13+</sup>
221
222exitPhotoBrowser(): void
223
224Exits the photo browser page.
225
226**Atomic service API**: This API can be used in atomic services since API version 13.
227
228**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
229
230### setPhotoBrowserUIElementVisibility<sup>13+</sup>
231
232setPhotoBrowserUIElementVisibility(elements: Array&lt;PhotoBrowserUIElement&gt;, isVisible: boolean): void
233
234Sets whether other UI elements are visible on the photo browser page. By default, other UI elements are visible.
235
236**Atomic service API**: This API can be used in atomic services since API version 13.
237
238**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
239
240**Parameters**
241
242| Name        | Type                                                            | Mandatory | Description               |
243|-------------|----------------------------------------------------------------| ----- |-------------------|
244| elements    | Array&lt;[PhotoBrowserUIElement](#photobrowseruielement13)&gt; | Yes| Other UI elements on the photo browser page.|
245| isVisible | boolean                                                        | Yes| Whether the specified UI elements are visible. The value **true** means that they are visible. The default value is **false**.            |
246
247### replacePhotoPickerPreview<sup>15+</sup>
248
249replacePhotoPickerPreview(originalUri: string, newUri: string, callback: AsyncCallback&lt;void&gt;): void
250
251Replaces the image selected by the user in the **PhotoPickerComponent** with the image edited by the application.
252
253**Atomic service API**: This API can be used in atomic services since API version 15.
254
255**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
256
257**Parameters**
258
259| Name        | Type                    |     Mandatory    | Description               |
260|-------------|----------------------------| -------------- |-------------------|
261| originalUri     | string  | Yes| URI of the original image, which will be replaced.|
262| 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.     |
263| callback   | AsyncCallback&lt;void&gt;   | Yes| Callback invoked when image replacement is complete.     |
264
265### saveTrustedPhotoAssets<sup>15+</sup>
266
267saveTrustedPhotoAssets(trustedUris: Array&lt;string&gt;, callback: AsyncCallback&lt;Array&lt;string&gt;&gt;, configs?: Array&lt;photoAccessHelper.PhotoCreationConfig&gt;, saveMode?: SaveMode): void
268
269Saves files in a URI list. Generally, this API is used together with [replacePhotoPickerPreview](#replacephotopickerpreview15) to save the new images or videos in the application sandbox path to Gallery.
270
271**Atomic service API**: This API can be used in atomic services since API version 15.
272
273**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
274
275**Parameters**
276
277| Name        | Type                                                            | Mandatory | Description               |
278|-------------|----------------------------------------------------------------| ----- |-------------------|
279| trustedUris     | Array&lt;string&gt; | Yes| URIs of the images or videos in the application sandbox path. Generally, **trustedUris** comes from **newUri** of new images generated by [replacePhotoPickerPreview](#replacephotopickerpreview15).|
280| callback  | AsyncCallback&lt;Array&lt;string&gt;&gt;          | Yes| URIs of the new files in Gallery.            |
281| configs | Array&lt;[photoAccessHelper.PhotoCreationConfig](arkts-apis-photoAccessHelper-i.md#photocreationconfig12)&gt;          | No| Configuration parameters corresponding to the original files.            |
282| saveMode | [SaveMode](#savemode15)           | No| Mode for saving the files.            |
283
284## BaseItemInfo
285
286Represents basic image and video information.
287
288**Atomic service API**: This API can be used in atomic services since API version 12.
289
290**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
291
292| Name    | Type   | Mandatory | Description                                               |
293|----------|--------|-----|---------------------------------------------------|
294| uri      | string                | No  | Image or video URI. This parameter is mandatory when **itemType** is **THUMBNAIL**. Otherwise, it is left empty.           |
295| mimeType | string                | No  | MIME type of the image or video. This parameter is mandatory when **itemType** is **THUMBNAIL**. Otherwise, it is left empty.      |
296| width    | number                | No  | Width of the image or video, in pixels. This parameter is mandatory when **itemType** is **THUMBNAIL**. Otherwise, it is left empty.      |
297| height   | number                | No  | Height of the image or video, in pixels. This parameter is mandatory when **itemType** is **THUMBNAIL**. Otherwise, it is left empty.      |
298| size     | number                | No  | Size of the image or video, in bytes. This parameter is mandatory when **itemType** is **THUMBNAIL**. Otherwise, it is left empty.    |
299| duration   | number                | No  | Video duration, in ms. This parameter is mandatory when **itemType** is **THUMBNAIL**. Otherwise, it is left empty. The value **-1** indicates an image.|
300
301## ItemInfo
302
303Represents image and video information. It inherits from [BaseItemInfo](#baseiteminfo), adding the private parameter **itemType**.
304
305
306**Atomic service API**: This API can be used in atomic services since API version 12.
307
308**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
309
310| Name    | Type   | Mandatory | Description                                               |
311|----------|--------|-----|---------------------------------------------------|
312| itemType | [ItemType](#itemtype) | No  | Type of the item, which can be **THUMBNAIL** or **CAMERA**.                     |
313
314## PhotoBrowserInfo
315
316Represents information about the photo browser page.
317
318**Atomic service API**: This API can be used in atomic services since API version 12.
319
320**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
321
322| Name    | Type   | Mandatory | Description    |
323|----------|--------|-----|---------|
324| animatorParams | [AnimatorParams](#animatorparams) | No  | Animation for entering or exiting the photo browser page.|
325
326## AnimatorParams
327
328Animation parameters for entering or exiting the photo browser page.
329
330**Atomic service API**: This API can be used in atomic services since API version 12.
331
332**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
333
334| Name    | Type   | Mandatory | Description          |
335|----------|--------|-----|--------------|
336| duration | number  | No           | Animation duration, in ms.|
337| curve      | [Curve](../apis-arkui/js-apis-curve.md#curve) &verbar; [ICurve](../apis-arkui/js-apis-curve.md#icurve9) &verbar; string | No  | Animation curve.       |
338
339## MaxSelected
340
341Represents the maximum number of media assets that can be selected at a time.
342
343**Atomic service API**: This API can be used in atomic services since API version 12.
344
345**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
346
347| Name    | Type   | Mandatory | Description    |
348|----------|--------|-----|---------|
349| data | Map&lt;[MaxCountType](#maxcounttype), number&gt; | No            | Maximum number of media assets (images, videos, or both) that can be selected at a time.|
350
351## SingleLineConfig
352
353Represents 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.
354
355**Atomic service API**: This API can be used in atomic services since API version 20.
356
357**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
358
359| Name| Type                                            | Mandatory| Description                                                                          |
360| ---- | ------------------------------------------------ | ---- | ------------------------------------------------------------------------------ |
361| itemDisplayRatio | [ItemDisplayRatio](#itemdisplayratio20) | No  | Aspect ratio for grid display. Both 1:1 and the original image aspect ratio are supported. The default value is 1:1.|
362| itemBorderRadius | [Length](../apis-arkui/arkui-ts/ts-types.md#length) &verbar; [BorderRadiuses](../apis-arkui/arkui-ts/ts-types.md#borderradiuses9) &verbar; [LocalizedBorderRadiuses](../apis-arkui/arkui-ts/ts-types.md#localizedborderradiuses12) | No  | Rounded corner radius for grid items.|
363| itemGap | [Length](../apis-arkui/arkui-ts/ts-types.md#length) | No  | Spacing between grid items.|
364
365## DataType
366
367Enumerates the types of data sent from **PickerController** to the **PhotoPickerComponent**.
368
369**Atomic service API**: This API can be used in atomic services since API version 12.
370
371**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
372
373| Name               | Value  | Description                                                                                                                |
374|-------------------|-----|--------------------------------------------------------------------------------------------------------------------|
375| SET_SELECTED_URIS | 1   | Send a list of selected items to instruct the **PhotoPickerComponent** to refresh the selection status. A string array needs to be passed in.<br>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.|
376| SET_ALBUM_URI | 2   | Send the selected album to instruct the **PhotoPickerComponent** to refresh the album data. A string array needs to be passed in.<br>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.|
377
378## ItemType
379
380Enumerates the types of the item clicked.
381
382**Atomic service API**: This API can be used in atomic services since API version 12.
383
384**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
385
386| Name               | Value  | Description        |
387|-------------------|-----|------------|
388| THUMBNAIL | 0   | Image or video (thumbnail).|
389| CAMERA | 1   | Camera item.   |
390
391## ClickType
392
393Enumerates the click operation types.
394
395**Atomic service API**: This API can be used in atomic services since API version 12.
396
397**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
398
399| Name               | Value  | Description                    |
400|-------------------|-----|------------------------|
401| SELECTED | 0   | Select (select an image or click a camera item).|
402| DESELECTED | 1   | Deselect (deselect an image).      |
403
404## PickerOrientation
405
406Enumerates the sliding preview directions of the Picker grid page.
407
408This 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.
409
410**Atomic service API**: This API can be used in atomic services since API version 12.
411
412**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
413
414| Name               | Value  | Description   |
415|-------------------|-----|-------|
416| VERTICAL | 0   | Vertical direction.|
417| HORIZONTAL | 1   | Horizontal direction.|
418
419## SelectMode
420
421Enumerates the select modes.
422
423**Atomic service API**: This API can be used in atomic services since API version 12.
424
425**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
426
427| Name               | Value  | Description   |
428|-------------------|-----|-------|
429| SINGLE_SELECT | 0   | Select a single option.|
430| MULTI_SELECT | 1   | Select multiple options.|
431
432## PickerColorMode
433
434Enumerates the Picker color modes.
435
436**Atomic service API**: This API can be used in atomic services since API version 12.
437
438**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
439
440| Name               | Value  | Description   |
441|-------------------|-----|-------|
442| AUTO | 0   | Same with the system.|
443| LIGHT | 1   | Light mode.|
444| DARK | 2   | Dark mode.|
445
446## ReminderMode
447
448Enumerates the types of the reminder when the number of selected items reaches the maximum.
449
450**Atomic service API**: This API can be used in atomic services since API version 12.
451
452**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
453
454| Name               | Value  | Description       |
455|-------------------|-----|-----------|
456| NONE | 0   | No reminder.     |
457| TOAST | 1   | Toast message.|
458| MASK | 2   | Grayed-out hint.    |
459
460## MaxCountType
461
462Enumerates the types of the maximum count.
463
464**Atomic service API**: This API can be used in atomic services since API version 12.
465
466**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
467
468| Name               | Value  | Description                       |
469|-------------------|-----|---------------------------|
470| TOTAL_MAX_COUNT | 0   | Total number of media assets (images and videos) that can be selected.                |
471| PHOTO_MAX_COUNT | 1   | Total number of images that can be selected. The value cannot be greater than **Total_MAX_Count**.|
472| VIDEO_MAX_COUNT | 2   | Total number of videos that can be selected. The value cannot be greater than **Total_MAX_Count**.|
473
474## PhotoBrowserRange
475
476Enumerates the view range on the photo browser page.
477
478**Atomic service API**: This API can be used in atomic services since API version 12.
479
480**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
481
482| Name               | Value  | Description                       |
483|-------------------|-----|---------------------------|
484| ALL | 0   | View all images and videos.                |
485| SELECTED_ONLY | 1   | View selected images and videos only.|
486
487## PhotoBrowserUIElement<sup>13+</sup>
488
489Represents other UI elements except the image preview component on the photo browser page.
490
491**Atomic service API**: This API can be used in atomic services since API version 13.
492
493**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
494
495| Name         | Value  | Description      |
496|-------------|-----|----------|
497| CHECKBOX    | 0   | Check box on the photo browser page. |
498| BACK_BUTTON | 1   | **Back** button on the photo browser page.|
499
500## SaveMode<sup>15+</sup>
501
502Enumerates the modes for saving images or videos.
503
504**Atomic service API**: This API can be used in atomic services since API version 15.
505
506**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
507
508| Name         | Value  | Description      |
509|-------------|-----|----------|
510| SAVE_AS     | 0   | Saves the image or video as a new one. |
511| 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.|
512
513## VideoPlayerState<sup>14+</sup>
514
515Enumerates the video playback states.
516
517**Atomic service API**: This API can be used in atomic services since API version 14.
518
519**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
520
521| Name               | Value  | Description                       |
522|-------------------|-----|---------------------------|
523| PLAYING | 0   | The video is being played.                |
524| PAUSED | 1   | Video playback is paused.|
525| STOPPED | 2   | Video playback is stopped.|
526| SEEK_START | 3   | Started dragging the progress bar.|
527| SEEK_FINISH | 4   | Finished dragging the progress bar.|
528
529## ItemDisplayRatio<sup>20+</sup>
530
531Enumerates the aspect ratios for grid display in single-line display mode.
532
533**Atomic service API**: This API can be used in atomic services since API version 20.
534
535**System capability**: SystemCapability.FileManagement.PhotoAccessHelper.Core
536
537| Name               | Value | Description          |
538| ------------------- | --- | -------------- |
539| SQUARE_RATIO        | 0   | 1:1 ratio.   |
540| ORIGINAL_SIZE_RATIO | 1   | Original image aspect ratio.|
541
542## Example
543
544```ts
545// xxx.ets
546import {
547  PhotoPickerComponent,
548  PickerController,
549  PickerOptions,
550  DataType,
551  BaseItemInfo,
552  ItemInfo,
553  PhotoBrowserInfo,
554  ItemType,
555  ClickType,
556  MaxCountType,
557  PhotoBrowserRange,
558  PhotoBrowserUIElement,
559  ItemsDeletedCallback,
560  ExceedMaxSelectedCallback,
561  CurrentAlbumDeletedCallback,
562  videoPlayStateChangedCallback,
563  VideoPlayerState
564} from '@ohos.file.PhotoPickerComponent';
565import { dataSharePredicates } from '@kit.ArkData';
566import { photoAccessHelper } from '@kit.MediaLibraryKit';
567
568@Entry
569@Component
570struct PickerDemo {
571  pickerOptions: PickerOptions = new PickerOptions();
572  @State pickerController: PickerController = new PickerController();
573  @State selectUris: string[] = [];
574  @State currentUri: string = '';
575  @State isBrowserShow: boolean = false;
576  private selectedItemsDeletedCallback: ItemsDeletedCallback =
577    (baseItemInfos: Array<BaseItemInfo>) => this.onSelectedItemsDeleted(baseItemInfos);
578  private exceedMaxSelectedCallback: ExceedMaxSelectedCallback =
579    (exceedMaxCountType: MaxCountType) => this.onExceedMaxSelected(exceedMaxCountType);
580  private currentAlbumDeletedCallback: CurrentAlbumDeletedCallback = () => this.onCurrentAlbumDeleted();
581  private videoPlayStateChangedCallback: videoPlayStateChangedCallback =
582    (state: VideoPlayerState) => this.videoPlayStateChanged(state);
583  private thumbnail: PixelMap[] = [];
584  private assets: photoAccessHelper.PhotoAsset[] = [];
585
586  aboutToAppear() {
587    this.pickerOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE;
588    this.pickerOptions.maxSelectNumber = 5;
589    this.pickerOptions.isSearchSupported = false;
590    this.pickerOptions.isPhotoTakingSupported = false;
591    this.pickerOptions.photoBrowserCheckboxPosition = [0.5, 0.5];
592    // Other attributes
593  }
594
595  private onSelect(uri: string): void {
596    // Add
597    if (uri) {
598      this.selectUris.push(uri);
599    }
600  }
601
602  private onDeselect(uri: string): void {
603    // Remove
604    if (uri) {
605      this.selectUris = this.selectUris.filter((item: string) => {
606        return item != uri;
607      })
608    }
609  }
610
611  private onItemClicked(itemInfo: ItemInfo, clickType: ClickType): boolean {
612    if (!itemInfo) {
613      return false;
614    }
615    let type: ItemType | undefined = itemInfo.itemType;
616    let uri: string | undefined = itemInfo.uri;
617    if (type === ItemType.CAMERA) {
618      // Click a camera item.
619      return true; // If true is returned, the system camera is started. If false is returned, the app processes its services.
620    } else {
621      if (clickType === ClickType.SELECTED) {
622        // The application performs its own service logic (not time-consuming operations, such as opening a large file using OpenSync).
623        if (uri) {
624          this.selectUris.push(uri);
625          this.pickerOptions.preselectedUris = [...this.selectUris];
626        }
627        return true; // If true is returned, the check box is selected. Otherwise, the check box is not selected.
628      } else {
629        if (uri) {
630          this.selectUris = this.selectUris.filter((item: string) => {
631            return item != uri;
632          });
633          this.pickerOptions.preselectedUris = [...this.selectUris];
634        }
635      }
636      return true;
637    }
638  }
639
640  private onEnterPhotoBrowser(photoBrowserInfo: PhotoBrowserInfo): boolean {
641    // Callback to be invoked when the photo browser page is displayed.
642    this.isBrowserShow = true;
643    return true;
644  }
645
646  private onExitPhotoBrowser(photoBrowserInfo: PhotoBrowserInfo): boolean {
647    // Callback to be invoked when the photo browser page is closed.
648    this.isBrowserShow = false;
649    return true;
650  }
651
652  private onPickerControllerReady(): void {
653    // 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.
654    let elements: number[] = [PhotoBrowserUIElement.BACK_BUTTON];
655    this.pickerController.setPhotoBrowserUIElementVisibility(elements, false); // Hide the Back button on the photo browser page.
656  }
657
658  private onPhotoBrowserChanged(browserItemInfo: BaseItemInfo): boolean {
659    // Callback to be invoked when the photo browser is swiped left or right.
660    this.currentUri = browserItemInfo.uri ?? '';
661    return true;
662  }
663
664  private onSelectedItemsDeleted(baseItemInfos: Array<BaseItemInfo>): void {
665    // Callback to be invoked when the selected image is deleted.
666  }
667
668  private onExceedMaxSelected(exceedMaxCountType: MaxCountType): void {
669    // Callback to be invoked when the number of selected items exceeds the maximum.
670  }
671
672  private onCurrentAlbumDeleted(): void {
673    // Callback to be invoked when the current album is deleted.
674  }
675
676  private videoPlayStateChanged(state: VideoPlayerState): void {
677    // Called when the video playback state changes.
678  }
679  build() {
680    Flex({
681      direction: FlexDirection.Column,
682      justifyContent: FlexAlign.Center,
683      alignItems: ItemAlign.Center
684    }) {
685      Column() {
686        if (this.isBrowserShow) {
687          // Back button of the application on the photo browser page.
688          Row() {
689            Button("Exit photo browser page").width('33%').height('8%').onClick(() => {
690              this.pickerController.exitPhotoBrowser();
691            })
692          }.margin({ bottom: 20 })
693        }
694
695        PhotoPickerComponent({
696          pickerOptions: this.pickerOptions,
697          // onSelect: (uri: string): void => this.onSelect(uri),
698          // onDeselect: (uri: string): void => this.onDeselect(uri),
699          onItemClicked: (itemInfo: ItemInfo, clickType: ClickType): boolean => this.onItemClicked(itemInfo,
700            clickType), // This API can replace the preceding two APIs.
701          onEnterPhotoBrowser: (photoBrowserInfo: PhotoBrowserInfo): boolean => this.onEnterPhotoBrowser(photoBrowserInfo),
702          onExitPhotoBrowser: (photoBrowserInfo: PhotoBrowserInfo): boolean => this.onExitPhotoBrowser(photoBrowserInfo),
703          onPickerControllerReady: (): void => this.onPickerControllerReady(),
704          onPhotoBrowserChanged: (browserItemInfo: BaseItemInfo): boolean => this.onPhotoBrowserChanged(browserItemInfo),
705          onSelectedItemsDeleted: this.selectedItemsDeletedCallback,
706          onExceedMaxSelected: this.exceedMaxSelectedCallback,
707          onCurrentAlbumDeleted: this.currentAlbumDeletedCallback,
708          onVideoPlayStateChanged: this.videoPlayStateChangedCallback,
709          pickerController: this.pickerController,
710        }).height('60%').width('100%')
711
712        // Simulate the selection bar at the bottom of the application.
713        if (this.isBrowserShow) {
714          Row() {
715            ForEach(this.assets, async (asset: photoAccessHelper.PhotoAsset, index) => {
716              if (asset.uri === this.currentUri) {
717                Image(this.thumbnail[index])
718                  .height('10%')
719                  .width('10%')
720                  .onClick(() => {
721                  })
722                  .borderWidth(1)
723                  .borderColor('red')
724              } else {
725                Image(this.thumbnail[index]).height('10%').width('10%').onClick(() => {
726                  this.pickerController.setData(DataType.SET_SELECTED_URIS, this.selectUris);
727                  this.pickerController.setPhotoBrowserItem(asset.uri, PhotoBrowserRange.ALL);
728                })
729              }
730            }, (uri: string) => JSON.stringify(uri))
731          }
732        } else {
733          Button('Preview').width('33%').height('5%').onClick(async () => {
734            if (this.selectUris.length > 0) {
735              this.thumbnail = [];
736              this.assets = [];
737              for (let selectUri of this.selectUris) {
738                let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
739                predicates.equalTo(photoAccessHelper.PhotoKeys.URI, selectUri);
740                let fetchOptions: photoAccessHelper.FetchOptions = {
741                  fetchColumns: [],
742                  predicates: predicates
743                };
744                let photoHelper = photoAccessHelper.getPhotoAccessHelper(getContext());
745                let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> =
746                  await photoHelper.getAssets(fetchOptions);
747                let asset = await fetchResult.getFirstObject()
748                this.assets.push(asset);
749                this.thumbnail.push(await asset.getThumbnail())
750              }
751              this.pickerController.setPhotoBrowserItem(this.selectUris[0], PhotoBrowserRange.SELECTED_ONLY);
752            }
753          })
754        }
755      }
756    }
757  }
758}
759```
760