• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Media Asset Management
2
3Your applications can use the APIs provided by the **mediaLibrary** module to perform operations on media assets such as audios, videos, images, and files.
4
5> **NOTE**
6>
7> Before developing features, read [MediaLibrary Overview](medialibrary-overview.md) to learn how to obtain a **MediaLibrary** instance and request the permissions to call the APIs of **MediaLibrary**.
8
9To maximize the application running efficiency, most **MediaLibrary** API calls are asynchronous in callback or promise mode. The following code samples use the promise mode. For details about the APIs, see [MediaLibrary API Reference](../reference/apis/js-apis-medialibrary.md).
10
11## Querying Media Assets
12
13You can query media assets by condition such as the media type, date, or album name.
14
15To do so, call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1), with a **MediaFetchOptions** object passed in to specify the conditions. In this object, **MediaFetchOptions.selections** are the retrieval conditions, and the enumerated values of **FileKey** are used as the column names of the conditions; **MediaFetchOptions.selectionArgs** are the values of the conditions. You can also specify **order** (sorting mode of the search result), **uri** (file URI), and **networkId** (network ID of the registered device) as the conditions.
16
17To obtain the object at the specified position (for example, the first, the last, or with the specified index) in the result set, call [FetchFileResult](../reference/apis/js-apis-medialibrary.md#fetchfileresult7). In this section, **getNextObject** is used cyclically to obtain all media assets in the result set.
18
19**Prerequisites**
20
21- You have obtained a **MediaLibrary** instance.
22- You have granted the permission **ohos.permission.READ_MEDIA**.
23
24### Querying Media Assets with the Specified Media Type
25
26The following describes how to obtain images.
27
28**How to Develop**
29
30To specify the media type as the retrieval condition, set **selections** to **FileKey.MEDIA_TYPE**.
31
32To specify the image as the media type, set **selectionArgs** to **MediaType.IMAGE**.
33
34```ts
35async function example() {
36  let fileKeyObj = mediaLibrary.FileKey;
37  let fileType = mediaLibrary.MediaType.IMAGE;
38  let option = {
39    selections: fileKeyObj.MEDIA_TYPE + '= ?',
40    selectionArgs: [fileType.toString()],
41  };
42  const context = getContext(this);
43  let media = mediaLibrary.getMediaLibrary(context);
44  const fetchFileResult = await media.getFileAssets(option);
45  fetchFileResult.getFirstObject().then(async (fileAsset) => {
46    console.log('getFirstObject.displayName : ' + fileAsset.displayName);
47    for (let i = 1; i < fetchFileResult.getCount(); i++) {
48      let fileAsset = await fetchFileResult.getNextObject();
49      console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
50    }
51  }).catch((err) => {
52    console.error('Failed to get first object: ' + err);
53  });
54}
55```
56
57### Querying Media Assets with the Specified Date
58
59The following describes how to obtain all the media assets that are added from the specified date. You can also use the modification date and shooting date as the retrieval conditions.
60
61To specify the date when the files are added as the retrieval condition, set **selections** to **FileKey.DATE_ADDED**.
62
63To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**.
64
65```ts
66async function example() {
67  let fileKeyObj = mediaLibrary.FileKey;
68  let option = {
69    selections: fileKeyObj.DATE_ADDED + '> ?',
70    selectionArgs: ['2022-8-5'],
71  };
72  const context = getContext(this);
73  let media = mediaLibrary.getMediaLibrary(context);
74  const fetchFileResult = await media.getFileAssets(option);
75  fetchFileResult.getFirstObject().then(async (fileAsset) => {
76    console.info('getFirstObject.displayName : ' + fileAsset.displayName);
77    for (let i = 1; i < fetchFileResult.getCount(); i++) {
78      let fileAsset = await fetchFileResult.getNextObject();
79      console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
80    }
81  }).catch((err) => {
82    console.error('Failed to get first object: ' + err);
83  });
84}
85```
86
87### Querying Media Assets and Sorting Them
88
89The following describes how to query images and sort them in descending order by the date when they are added. You can also sort them in ascending order.
90
91To sort files in descending order by the date when they are added, set **order** to **FileKey.DATE_ADDED + " DESC"**.
92
93```ts
94async function example() {
95  let fileKeyObj = mediaLibrary.FileKey;
96  let fileType = mediaLibrary.MediaType.IMAGE;
97  let option = {
98    selections: fileKeyObj.MEDIA_TYPE + '= ?',
99    selectionArgs: [fileType.toString()],
100    order: fileKeyObj.DATE_ADDED + " DESC",
101  };
102  const context = getContext(this);
103  let media = mediaLibrary.getMediaLibrary(context);
104  const fetchFileResult = await media.getFileAssets(option);
105  fetchFileResult.getFirstObject().then(async (fileAsset) => {
106    console.info('getFirstObject.displayName : ' + fileAsset.displayName);
107    for (let i = 1; i < fetchFileResult.getCount(); i++) {
108      let fileAsset = await fetchFileResult.getNextObject();
109      console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
110    }
111  }).catch((err) => {
112    console.error('Failed to get first object: ' + err);
113  });
114}
115```
116
117### Querying Media Assets with the Specified Album Name
118
119The following describes how to query media assets in **myAlbum**.
120
121To specify the album name as the retrieval condition, set **selections** to **FileKey.ALBUM_NAME**.
122
123To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**.
124
125```ts
126async function example() {
127  let fileKeyObj = mediaLibrary.FileKey;
128  let option = {
129    selections: fileKeyObj.ALBUM_NAME + '= ?',
130    selectionArgs: ['myAlbum'],
131  };
132  const context = getContext(this);
133  let media = mediaLibrary.getMediaLibrary(context);
134  const fetchFileResult = await media.getFileAssets(option);
135  if (albumList.length > 0) {
136    fetchFileResult.getFirstObject().then((album) => {
137      console.info('getFirstObject.displayName : ' + album.albumName);
138    }).catch((err) => {
139      console.error('Failed to get first object: ' + err);
140    });
141  } else {
142    console.info('getAlbum list is: 0');
143  }
144}
145```
146
147## Obtaining Images and Videos in an Album
148
149You can obtain media assets in an album in either of the following ways:
150- Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified, as described in [Querying Media Assets with the Specfied Album Name](#querying-media-assets-with-the-specified-album-name).
151- Call [Album.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-3) to obtain an **Album** instance, so as to obtain the media assets in it.
152
153**Prerequisites**
154
155- You have obtained a **MediaLibrary** instance.
156- You have granted the permission **ohos.permission.READ_MEDIA**.
157
158**How to Develop**
159
160The following describes how to obtain videos in an album named **New Album 1**.
161
1621. Create a retrieval condition for obtaining the target **Album** instance.
163
164```ts
165let fileKeyObj = mediaLibrary.FileKey;
166let AlbumNoArgsFetchOp = {
167  selections: fileKeyObj.ALBUM_NAME + '= ?',
168  selectionArgs:['New Album 1']
169}
170```
171
1722. Create a retrieval condition for obtaining videos in the target album.
173
174```ts
175let fileKeyObj = mediaLibrary.FileKey;
176let videoType = mediaLibrary.MediaType.VIDEO;
177let videoFetchOp  = {
178  selections: fileKeyObj.MEDIA_TYPE + '= ?',
179  selectionArgs: [videoType.toString()],
180}
181```
182
1833. Call **Album.getFileAssets** to obtain the videos in the target album.
184
185Complete sample code:
186
187```ts
188async function getCameraImagePromise() {
189  const context = getContext(this);
190  let media = mediaLibrary.getMediaLibrary(context);
191  let fileKeyObj = mediaLibrary.FileKey;
192  let videoType = mediaLibrary.MediaType.VIDEO;
193  let videoFetchOp = {
194    selections: fileKeyObj.MEDIA_TYPE + '= ?',
195    selectionArgs: [videoType.toString()],
196  }
197  let AlbumNoArgsFetchOp = {
198    selections: fileKeyObj.ALBUM_NAME + '= ?',
199    selectionArgs:['New Album 1']
200  }
201
202  let albumList = await media.getAlbums(AlbumNoArgsFetchOp);
203  if (albumList.length > 0) {
204    const album = albumList[0];
205    let fetchFileResult = await album.getFileAssets(videoFetchOp);
206    let count = fetchFileResult.getCount();
207    console.info("get mediaLibrary VIDEO number", count);
208  } else {
209    console.info('getAlbum list is: 0');
210  }
211}
212```
213
214## Obtaining the Thumbnail of an Image or a Video
215
216You can call [FileAsset.getThumbnail](../reference/apis/js-apis-medialibrary.md#getthumbnail8-2) with the thumbnail size passed in to obtain the thumbnail of an image or a video. Your application can use thumbnails to offer a quick preview on images and videos.
217
218**Prerequisites**
219
220- You have obtained a **MediaLibrary** instance.
221- You have granted the permission **ohos.permission.READ_MEDIA**.
222
223### Obtaining the Thumbnail of an Image
224
225The following describes how to obtain the thumbnail (size: 720 x 720) of the first image in the album.
226
227**How to Develop**
228
2291. Create a retrieval condition for obtaining images in the target album.
2302. Call **getFileAssets** to obtain the images in the target album.
2313. Call **getFirstObject** to obtain the first image among all the images obtained.
2324. Call **getThumbnail** to obtain the thumbnail of the first image.
233
234```ts
235async function getFirstThumbnailPromise() {
236  const context = getContext(this);
237  let media = mediaLibrary.getMediaLibrary(context);
238  let fileKeyObj = mediaLibrary.FileKey;
239  let imageType = mediaLibrary.MediaType.IMAGE;
240  let imagesFetchOp = {
241    selections: fileKeyObj.MEDIA_TYPE + '= ?',
242    selectionArgs: [imageType.toString()],
243  }
244
245  let size = { width: 720, height: 720 };
246  const fetchFileResult = await media.getFileAssets(imagesFetchOp);
247  if (fetchFileResult === undefined) {
248    console.error("get image failed with error");
249    return;
250  } else {
251    const asset = await fetchFileResult.getFirstObject();
252    asset.getThumbnail(size).then((pixelMap) => {
253      pixelMap.getImageInfo().then((info) => {
254        console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height);
255      }).catch((err) => {
256        console.error("getImageInfo failed with error: " + err);
257      });
258    }).catch((err) => {
259      console.error("getImageInfo failed with error: " + err);
260    });
261  }
262}
263```
264
265## Creating a Media Asset
266
267You can call [MediaLibrary.createAsset](../reference/apis/js-apis-medialibrary.md#createasset8-1) to create a media asset.
268
269**Prerequisites**
270
271- You have obtained a **MediaLibrary** instance.
272- You have granted the permission **ohos.permission.WRITE_MEDIA**.
273- [You have obtained a public directory](medialibrary-filepath-guidelines.md).
274
275The following describes how to create a file of the **MediaType.FILE** type.
276
277```ts
278async function example() {
279  let mediaType = mediaLibrary.MediaType.FILE;
280  let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
281  const context = getContext(this);
282  let media = mediaLibrary.getMediaLibrary(context);
283  const path = await media.getPublicDirectory(DIR_DOCUMENTS);
284  media.createAsset(mediaType, "testFile.text", path).then((asset) => {
285    console.info("createAsset successfully:"+ JSON.stringify(asset));
286  }).catch((err) => {
287    console.error("createAsset failed with error: " + err);
288  });
289}
290```
291
292## Moving a Media Asset to the Recycle Bin
293
294You can use [FileAsset.trash](../reference/apis/js-apis-medialibrary.md#trash8) to move a media asset to the recycle bin.
295
296By default, files in the recycle bin will be stored for 30 days before being permanently removed. During this period, you can set **isTrash** in **trash** to **false** to recover the files. Application users can also recover the files through the system applications **Files** or **Gallery**.
297
298**Prerequisites**
299
300- You have obtained a **MediaLibrary** instance.
301- You have granted the permission **ohos.permission.WRITE_MEDIA**.
302
303The following describes how to move the first file in the result set to the recycle bin.
304
305**How to Develop**
306
3071. Create a retrieval condition for obtaining images in the target album.
3082. Call **getFileAssets** to obtain the images in the target album.
3093. Call **getFirstObject** to obtain the first image among all the images obtained.
3104. Call **trash** to move the first image to the recycle bin.
311
312```ts
313async function example() {
314  let fileKeyObj = mediaLibrary.FileKey;
315  let fileType = mediaLibrary.MediaType.FILE;
316  let option = {
317    selections: fileKeyObj.MEDIA_TYPE + '= ?',
318    selectionArgs: [fileType.toString()],
319  };
320  const context = getContext(this);
321  let media = mediaLibrary.getMediaLibrary(context);
322  const fetchFileResult = await media.getFileAssets(option);
323  let asset = await fetchFileResult.getFirstObject();
324  if (asset === undefined) {
325    console.error('asset not exist');
326    return;
327  }
328  // Void callback.
329  asset.trash(true).then(() => {
330    console.info("trash successfully");
331  }).catch((err) => {
332    console.error("trash failed with error: " + err);
333  });
334}
335```
336
337## Renaming a Media Asset
338
339To rename a media asset, modify the **FileAsset.displayName** attribute (which specifies the displayed file name, including the file name extension) and commit the modification through [FileAsset.commitModify](../reference/apis/js-apis-medialibrary.md#commitmodify8-1).
340
341Before renaming a file, you must obtain the file, for example, by calling [FetchFileResult](../reference/apis/js-apis-medialibrary.md#fetchfileresult7).
342
343**Prerequisites**
344
345- You have obtained a **MediaLibrary** instance.
346- You have granted the permission **ohos.permission.WRITE_MEDIA**.
347
348The following describes how to rename the first file in the result set as **newImage.jpg**.
349
350**How to Develop**
351
3521. Create a retrieval condition for obtaining images in the target album.
3532. Call **getFileAssets** to obtain the images in the target album.
3543. Call **getFirstObject** to obtain the first image among all the images obtained.
3554. Rename the image as **newImage.jpg**.
3565. Call **FileAsset.commitModify** to commit the modification to the database.
357
358```ts
359async function example() {
360  let fileKeyObj = mediaLibrary.FileKey;
361  let fileType = mediaLibrary.MediaType.IMAGE;
362  let option = {
363    selections: fileKeyObj.MEDIA_TYPE + '= ?',
364    selectionArgs: [fileType.toString()],
365  };
366  const context = getContext(this);
367  let media = mediaLibrary.getMediaLibrary(context);
368  const fetchFileResult = await media.getFileAssets(option);
369  let asset = await fetchFileResult.getFirstObject();
370  if (asset === undefined) {
371    console.error('asset not exist');
372    return;
373  }
374  asset.displayName = 'newImage.jpg';
375  // Void callback.
376  asset.commitModify((err) => {
377    if (err) {
378      console.error('fileRename Failed ');
379      return;
380    }
381    console.info('fileRename successful.');
382  });
383}
384```
385