• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# @ohos.file.sendablePhotoAccessHelper (相册管理模块)(系统接口)
2
3该模块基于[Sendable](../../arkts-utils/arkts-sendable.md)对象,提供相册管理模块能力,包括创建相册以及访问、修改相册中的媒体数据信息等。
4
5> **说明:**
6>
7> - 本模块首批接口从API version 12开始支持。后续版本的新增接口,采用上角标单独标记接口的起始版本。
8> - 当前页面仅包含本模块的系统接口,其他公开接口参见[@ohos.file.sendablePhotoAccessHelper (基于Sendable对象的相册管理模块)](js-apis-sendablePhotoAccessHelper.md)。
9
10## 导入模块
11
12```ts
13import { sendablePhotoAccessHelper } from '@kit.MediaLibraryKit';
14```
15
16## sendablePhotoAccessHelper.getPhotoAccessHelper<sup>19+</sup>
17
18getPhotoAccessHelper(context: Context, userId: number): PhotoAccessHelper
19
20支持跨用户获取相册管理模块的实例,用于访问和修改相册中的媒体文件。
21
22​**模型约束**:此接口仅可在Stage模型下使用。
23
24**系统接口**:此接口为系统接口。
25
26**系统能力**:SystemCapability.FileManagement.PhotoAccessHelper.Core
27
28**参数:**
29
30| 参数名  | 类型    | 必填 | 说明                       |
31| ------- | ------- | ---- | -------------------------- |
32| context | [Context](../apis-ability-kit/js-apis-inner-application-context.md) | 是   | 传入Ability实例的上下文。 |
33| userId | number | 是   | 传入待访问用户的id。 |
34
35**返回值:**
36
37| 类型                            | 说明    |
38| ----------------------------- | :---- |
39| [PhotoAccessHelper](#photoaccesshelper) | 相册管理模块的实例。 |
40
41**错误码:**
42
43接口抛出错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)。
44
45| 错误码ID | 错误信息 |
46| -------- | ---------------------------------------- |
47| 401 | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
48
49**示例:**
50
51```ts
52// 此处获取的phAccessHelper实例为全局对象,后续使用到phAccessHelper的地方默认为使用此处获取的对象,如未添加此段代码报phAccessHelper未定义的错误请自行添加。
53// 请在组件内获取context,确保this.getUiContext().getHostContext()返回结果为UIAbilityContext
54import { common } from '@kit.AbilityKit';
55
56@Entry
57@Component
58struct Index {
59  build() {
60    Row() {
61      Button("example").onClick(async () => {
62        let context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext;
63        // 此处101表示其他用户空间的userid
64        let phAccessHelper = sendablePhotoAccessHelper.getPhotoAccessHelper(context, 101);
65      }).width('100%')
66    }
67    .height('90%')
68  }
69}
70```
7172## PhotoAccessHelper
73
74### createAsset
75
76createAsset(displayName: string): Promise&lt;PhotoAsset&gt;
77
78指定待创建的图片或者视频的文件名,创建图片或视频资源,使用Promise方式返回结果。
79
80待创建的文件名参数规格为:
81- 应包含有效文件主名和图片或视频扩展名。
82- 文件名字符串长度为1~255。
83- 文件主名中不允许出现的非法英文字符。<br>API18开始,非法字符包括:\ / : * ? " < > |<br>API10-17,非法字符包括:. .. \ / : * ? " ' ` < > | { } [ ]
84
85**系统接口**:此接口为系统接口。
86
87**系统能力**:SystemCapability.FileManagement.PhotoAccessHelper.Core
88
89**需要权限**:ohos.permission.WRITE_IMAGEVIDEO
90
91**参数:**
92
93| 参数名      | 类型   | 必填 | 说明                       |
94| ----------- | ------ | ---- | -------------------------- |
95| displayName | string | 是   | 创建的图片或者视频文件名。 |
96
97**返回值:**
98
99| 类型                                     | 说明                                    |
100| ---------------------------------------- | --------------------------------------- |
101| Promise&lt;[PhotoAsset](#photoasset)&gt; | Promise对象,返回创建的图片和视频结果。 |
102
103**错误码:**
104
105接口抛出错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[文件管理错误码](../apis-core-file-kit/errorcode-filemanagement.md)。
106
107| 错误码ID | 错误信息                                                     |
108| -------- | ------------------------------------------------------------ |
109| 202      | Called by non-system application.                            |
110| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
111| 201      | Permission denied.                                           |
112| 13900020 | Invalid argument.                                            |
113| 14000001 | Invalid display name.                                        |
114| 14000011 | Internal system error                                        |
115
116**示例:**
117
118phAccessHelper的创建请参考[@ohos.file.sendablePhotoAccessHelper (基于Sendable对象的相册管理模块)](js-apis-sendablePhotoAccessHelper.md)的示例使用。
119
120```ts
121async function example(phAccessHelper: sendablePhotoAccessHelper.PhotoAccessHelper) {
122  console.info('createAssetDemo');
123  try {
124    let testFileName: string = 'testFile' + Date.now() + '.jpg';
125    let photoAsset: sendablePhotoAccessHelper.PhotoAsset = await phAccessHelper.createAsset(testFileName);
126    console.info('createAsset file displayName' + photoAsset.displayName);
127    console.info('createAsset successfully');
128  } catch (err) {
129    console.error(`createAsset failed, error: ${err.code}, ${err.message}`);
130  }
131}
132```
133
134### createAsset
135
136createAsset(displayName: string, options: PhotoCreateOptions): Promise&lt;PhotoAsset&gt;
137
138指定待创建的图片或者视频的文件名和创建选项,创建图片或视频资源,使用Promise方式返回结果。
139
140待创建的文件名参数规格为:
141- 应包含有效文件主名和图片或视频扩展名。
142- 文件名字符串长度为1~255。
143- 文件主名中不允许出现的非法英文字符。<br>API18开始,非法字符包括:\ / : * ? " < > |<br>API10-17,非法字符包括:. .. \ / : * ? " ' ` < > | { } [ ]
144
145**系统接口**:此接口为系统接口。
146
147**系统能力**:SystemCapability.FileManagement.PhotoAccessHelper.Core
148
149**需要权限**:ohos.permission.WRITE_IMAGEVIDEO
150
151**参数:**
152
153| 参数名      | 类型                                                         | 必填 | 说明                       |
154| ----------- | ------------------------------------------------------------ | ---- | -------------------------- |
155| displayName | string                                                       | 是   | 创建的图片或者视频文件名。 |
156| options     | [PhotoCreateOptions](js-apis-photoAccessHelper-sys.md#photocreateoptions) | 是   | 图片或视频的创建选项。     |
157
158**返回值:**
159
160| 类型                                     | 说明                                    |
161| ---------------------------------------- | --------------------------------------- |
162| Promise&lt;[PhotoAsset](#photoasset)&gt; | Promise对象,返回创建的图片和视频结果。 |
163
164**错误码:**
165
166接口抛出错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[文件管理错误码](../apis-core-file-kit/errorcode-filemanagement.md)。
167
168| 错误码ID | 错误信息                                                     |
169| -------- | ------------------------------------------------------------ |
170| 202      | Called by non-system application.                            |
171| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
172| 201      | Permission denied.                                           |
173| 13900020 | Invalid argument.                                            |
174| 14000001 | Invalid display name.                                        |
175| 14000011 | Internal system error                                        |
176
177**示例:**
178
179phAccessHelper的创建请参考[@ohos.file.sendablePhotoAccessHelper (基于Sendable对象的相册管理模块)](js-apis-sendablePhotoAccessHelper.md)的示例使用。
180
181```ts
182async function example(phAccessHelper: sendablePhotoAccessHelper.PhotoAccessHelper) {
183  console.info('createAssetDemo');
184  try {
185    let testFileName:string = 'testFile' + Date.now() + '.jpg';
186    let createOption: photoAccessHelper.PhotoCreateOptions = {
187      subtype: photoAccessHelper.PhotoSubtype.DEFAULT
188    }
189    let photoAsset: sendablePhotoAccessHelper.PhotoAsset = await phAccessHelper.createAsset(testFileName, createOption);
190    console.info('createAsset file displayName' + photoAsset.displayName);
191    console.info('createAsset successfully');
192  } catch (err) {
193    console.error(`createAsset failed, error: ${err.code}, ${err.message}`);
194  }
195}
196```
197
198### getHiddenAlbums
199
200getHiddenAlbums(mode: HiddenPhotosDisplayMode, options?: FetchOptions): Promise&lt;FetchResult&lt;Album&gt;&gt;
201
202根据隐藏文件显示模式和检索选项获取系统中的隐藏相册,使用Promise方式返回结果。
203
204**系统接口**:此接口为系统接口。
205
206**需要权限**:ohos.permission.READ_IMAGEVIDEOohos.permission.MANAGE_PRIVATE_PHOTOS
207
208**系统能力**:SystemCapability.FileManagement.PhotoAccessHelper.Core
209
210**参数:**
211
212| 参数名  | 类型                                                         | 必填 | 说明                                           |
213| ------- | ------------------------------------------------------------ | ---- | ---------------------------------------------- |
214| mode    | [HiddenPhotosDisplayMode](js-apis-photoAccessHelper-sys.md#hiddenphotosdisplaymode11) | 是   | 隐藏文件显示模式。                               |
215| options | [FetchOptions](arkts-apis-photoAccessHelper-i.md#fetchoptions)    | 否   | 检索选项,不填时默认根据隐藏文件显示模式检索。 |
216
217**返回值:**
218
219| 类型                                                         | 说明                                |
220| ------------------------------------------------------------ | ----------------------------------- |
221| Promise&lt;[FetchResult](arkts-apis-photoAccessHelper-FetchResult.md)&lt;[Album](#album)&gt;&gt; | Promise对象,返回获取相册的结果集。 |
222
223**错误码:**
224
225接口抛出错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[文件管理错误码](../apis-core-file-kit/errorcode-filemanagement.md)。
226
227| 错误码ID | 错误信息                                                     |
228| -------- | ------------------------------------------------------------ |
229| 201      | Permission verification failed, usually the result returned by VerifyAccessToken. |
230| 202      | Permission verification failed, application which is not a system application uses system API. |
231| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
232| 14000011 | Internal system error.                                        |
233
234**示例:**
235
236phAccessHelper的创建请参考[@ohos.file.sendablePhotoAccessHelper (基于Sendable对象的相册管理模块)](js-apis-sendablePhotoAccessHelper.md)的示例使用。
237
238```ts
239import { dataSharePredicates } from '@kit.ArkData';
240import { BusinessError } from '@kit.BasicServicesKit';
241
242// 获取系统预置的隐藏相册。
243async function getSysHiddenAlbum(phAccessHelper: sendablePhotoAccessHelper.PhotoAccessHelper) {
244  console.info('getSysHiddenAlbumDemo');
245  phAccessHelper.getHiddenAlbums(photoAccessHelper.HiddenPhotosDisplayMode.ASSETS_MODE)
246    .then( async (fetchResult) => {
247      if (fetchResult === undefined) {
248        console.error('getSysHiddenAlbumPromise fetchResult is undefined');
249        return;
250      }
251      let hiddenAlbum: sendablePhotoAccessHelper.Album = await fetchResult.getFirstObject();
252      console.info('getAlbumsPromise successfully, albumUri: ' + hiddenAlbum.albumUri);
253      fetchResult.close();
254    }).catch((err: BusinessError) => {
255      console.error(`getSysHiddenAlbumPromise failed with err: ${err.code}, ${err.message}`);
256    });
257}
258
259// 获取隐藏相册-相册视图,即系统中包含隐藏文件的相册(不包含系统预置的隐藏相册本身和回收站相册)。
260async function getHiddenAlbumsView(phAccessHelper: sendablePhotoAccessHelper.PhotoAccessHelper) {
261  console.info('getHiddenAlbumsViewDemo');
262  phAccessHelper.getHiddenAlbums(photoAccessHelper.HiddenPhotosDisplayMode.ALBUMS_MODE).then( async (fetchResult) => {
263    if (fetchResult === undefined) {
264      console.error('getHiddenAlbumsViewPromise fetchResult is undefined');
265      return;
266    }
267    let albums: Array<sendablePhotoAccessHelper.Album> = await fetchResult.getAllObjects();
268    console.info('getHiddenAlbumsViewPromise successfully, albums size: ' + albums.length);
269
270    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
271    let fetchOption: photoAccessHelper.FetchOptions = {
272      fetchColumns: [],
273      predicates: predicates
274    };
275    for (let i = 0; i < albums.length; i++) {
276      // 获取相册中的隐藏文件。
277      albums[i].getAssets(fetchOption).then((assetFetchResult) => {
278        console.info('album get hidden assets successfully, getCount: ' + assetFetchResult.getCount());
279      }).catch((err: BusinessError) => {
280        console.error(`album get hidden assets failed with error: ${err.code}, ${err.message}`);
281      });
282    }
283    fetchResult.close();
284  }).catch((err: BusinessError) => {
285    console.error(`getHiddenAlbumsViewPromise failed with err: ${err.code}, ${err.message}`);
286  });
287}
288```
289
290## PhotoAsset
291
292提供封装文件属性的方法。
293
294### requestSource
295
296requestSource(): Promise&lt;number&gt;
297
298打开源文件并返回fd,该方法使用Promise形式来返回结果。
299
300**系统接口**:此接口为系统接口。
301
302**需要权限**:ohos.permission.READ_IMAGEVIDEO
303
304**系统能力**:SystemCapability.FileManagement.PhotoAccessHelper.Core
305
306**返回值:**
307
308| 类型                  | 说明                        |
309| --------------------- | --------------------------- |
310| Promise&lt;number&gt; | Promise对象,返回源文件fd。 |
311
312**错误码:**
313
314接口抛出错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[文件管理错误码](../apis-core-file-kit/errorcode-filemanagement.md)。
315
316| 错误码ID | 错误信息                                                     |
317| -------- | ------------------------------------------------------------ |
318| 201      | Permission denied.                                           |
319| 202      | Called by non-system application.                            |
320| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types. |
321| 14000011 | Internal system error                                        |
322
323**示例:**
324
325phAccessHelper的创建请参考[@ohos.file.sendablePhotoAccessHelper (基于Sendable对象的相册管理模块)](js-apis-sendablePhotoAccessHelper.md)的示例使用。
326
327```ts
328import { dataSharePredicates } from '@kit.ArkData';
329import { common } from '@kit.AbilityKit';
330
331async function example(phAccessHelper: sendablePhotoAccessHelper.PhotoAccessHelper) {
332  try {
333    console.info('requsetSourcePromiseDemo')
334    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
335    let fetchOptions: photoAccessHelper.FetchOptions = {
336      fetchColumns: [],
337      predicates: predicates
338    };
339    let fetchResult: sendablePhotoAccessHelper.FetchResult<sendablePhotoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOptions);
340    let photoAsset: sendablePhotoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
341    let fd = await photoAsset.requestSource();
342    console.info('Source fd is ' + fd);
343  } catch (err) {
344    console.error(`requsetSourcePromiseDemo failed with error: ${err.code}, ${err.message}`);
345  }
346}
347```
348
349### getAnalysisData
350
351getAnalysisData(analysisType: AnalysisType): Promise\<string>
352
353根据智慧分析类型获取指定分析结果数据。
354
355**系统接口**:此接口为系统接口。
356
357**需要权限**:ohos.permission.READ\_IMAGEVIDEO
358
359**系统能力**:SystemCapability.FileManagement.PhotoAccessHelper.Core
360
361**参数:**
362
363| 参数名       | 类型                                                         | 必填 | 说明                     |
364| :----------- | :----------------------------------------------------------- | :--- | :----------------------- |
365| analysisType | [AnalysisType](js-apis-photoAccessHelper-sys.md#analysistype11) | 是   | 需要获取的智慧分析类型。 |
366
367**返回值:**
368
369| 类型                | 说明                                |
370| :------------------ | :---------------------------------- |
371| Promise&lt;string&gt; | Promise对象,返回指定分析数据结果。 |
372
373**错误码:**
374
375接口抛出错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[文件管理错误码](../apis-core-file-kit/errorcode-filemanagement.md)。
376
377| 错误码ID | 错误信息                                                     |
378| :------- | :----------------------------------------------------------- |
379| 201      | Permission denied.                                           |
380| 202      | Called by non-system application.                            |
381| 401      | Parameter error. Possible causes: 1. Mandatory parameters are left unspecified; 2. Incorrect parameter types; 3. Parameter verification failed. |
382| 14000011 | Internal system error                                        |
383
384**示例:**
385
386phAccessHelper的创建请参考[@ohos.file.sendablePhotoAccessHelper (基于Sendable对象的相册管理模块)](js-apis-sendablePhotoAccessHelper.md)的示例使用。
387
388```ts
389import { dataSharePredicates } from '@kit.ArkData';
390import { common } from '@kit.AbilityKit';
391
392async function example(phAccessHelper: sendablePhotoAccessHelper.PhotoAccessHelper) {
393  try {
394    console.info('getAnalysisDataDemo')
395    let fetchOptions: photoAccessHelper.FetchOptions = {
396      fetchColumns: [],
397      predicates: new dataSharePredicates.DataSharePredicates()
398    }
399    let fetchResult: sendablePhotoAccessHelper.FetchResult<sendablePhotoAccessHelper.PhotoAsset> =
400      await phAccessHelper.getAssets(fetchOptions);
401    let photoAsset: sendablePhotoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
402    if (photoAsset != undefined) {
403      let analysisData: string = await photoAsset.getAnalysisData(
404        photoAccessHelper.AnalysisType.ANALYSIS_OCR);
405      console.info('get ocr result: ' + JSON.stringify(analysisData));
406    }
407    fetchResult.close();
408  } catch (err) {
409    console.error(`getAnalysisDataDemofailed with error: ${err.code}, ${err.message}`);
410  }
411}
412```
413
414## Album
415
416实体相册
417
418### getFaceId<sup>13+</sup>
419
420getFaceId(): Promise\<string>
421
422获取人像相册或合影相册的封面人脸标识。
423
424**系统接口**:此接口为系统接口。
425
426**需要权限**:ohos.permission.READ\_IMAGEVIDEO
427
428**系统能力**:SystemCapability.FileManagement.PhotoAccessHelper.Core
429
430**返回值:**
431
432| 类型                | 说明                                |
433| :------------------ | :---------------------------------- |
434| Promise&lt;string&gt; | Promise对象,人像相册返回tag_id,合影相册返回group_tag,未找到返回空字符串。 |
435
436**错误码:**
437
438接口抛出错误码的详细介绍请参见[通用错误码](../errorcode-universal.md)和[文件管理错误码](../apis-core-file-kit/errorcode-filemanagement.md)。
439
440| 错误码ID | 错误信息                                                     |
441| :------- | :----------------------------------------------------------- |
442| 201      | Permission denied.                                           |
443| 202      | Called by non-system application.                            |
444| 14000011 | Internal system error                                        |
445
446**示例:**
447
448phAccessHelper的创建请参考[@ohos.file.sendablePhotoAccessHelper (基于Sendable对象的相册管理模块)](js-apis-sendablePhotoAccessHelper.md)的示例使用。
449
450```ts
451import { dataSharePredicates } from '@kit.ArkData';
452import { common } from '@kit.AbilityKit';
453
454async function example(phAccessHelper: sendablePhotoAccessHelper.PhotoAccessHelper) {
455  try {
456    console.info('getFaceIdDemo');
457    let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
458    predicates.equalTo("user_display_level", 1);
459    let fetchOptions: photoAccessHelper.FetchOptions = {
460      fetchColumns: [],
461      predicates: predicates
462    };
463    let fetchResult =
464      await phAccessHelper.getAlbums(sendablePhotoAccessHelper.AlbumType.SMART,
465        sendablePhotoAccessHelper.AlbumSubtype.PORTRAIT,
466        fetchOptions);
467    let album = await fetchResult?.getFirstObject();
468    let faceId = await album?.getFaceId();
469    console.info(`getFaceId successfully, faceId: ${faceId}`);
470    fetchResult.close();
471  } catch (err) {
472    console.error(`getFaceId failed with err: ${err.code}, ${err.message}`);
473  }
474}
475```
476
477## AlbumType
478
479枚举,相册类型,表示是用户相册还是系统预置相册。
480
481**系统能力**:SystemCapability.FileManagement.PhotoAccessHelper.Core
482
483| 名称  | 值   | 说明                                           |
484| ----- | ---- | ---------------------------------------------- |
485| SMART | 4096 | 智慧分析相册。**系统接口**:此接口为系统接口。 |
486
487## AlbumSubtype
488
489枚举,相册子类型,表示具体的相册类型。
490
491**系统能力**:SystemCapability.FileManagement.PhotoAccessHelper.Core
492
493| 名称                  | 值   | 说明                                                       |
494| --------------------- | ---- | ---------------------------------------------------------- |
495| HIDDEN                | 1027 | 隐藏相册。**系统接口**:此接口为系统接口。                 |
496| TRASH                 | 1028 | 回收站。**系统接口**:此接口为系统接口。                   |
497| SCREENSHOT            | 1029 | 截屏和录屏相册。**系统接口**:此接口为系统接口。           |
498| CAMERA                | 1030 | 相机拍摄的照片和视频相册。**系统接口**:此接口为系统接口。 |
499| SOURCE\_GENERIC       | 2049 | 来源相册。**系统接口**:此接口为系统接口。                 |
500| CLASSIFY              | 4097 | 分类相册。**系统接口**:此接口为系统接口。                 |
501| GEOGRAPHY\_LOCATION   | 4099 | 地图相册。**系统接口**:此接口为系统接口。                 |
502| GEOGRAPHY\_CITY       | 4100 | 城市相册。**系统接口**:此接口为系统接口。                 |
503| SHOOTING\_MODE        | 4101 | 拍摄模式相册。**系统接口**:此接口为系统接口。             |
504| PORTRAIT              | 4102 | 人像相册。**系统接口**:此接口为系统接口。                 |
505| GROUP_PHOTO           | 4103 | 合影相册。**系统接口**:此接口为系统接口。                 |
506| HIGHLIGHT             | 4104 | 时刻相册。**系统接口**:此接口为系统接口。                 |
507| HIGHLIGHT_SUGGESTIONS | 4105 | 时刻建议相册。**系统接口**:此接口为系统接口。             |