medialibrary-resource-guidelines.md 14.5 KB
Newer Older
G
Gloria 已提交
1 2 3 4 5 6 7 8
# Media Asset Management

Your applications can use the APIs provided by the **mediaLibrary** module to perform operations on media assets such as audios, videos, images, and files.

> **NOTE**
>
> 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**.

G
Gloria 已提交
9
To 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).
G
Gloria 已提交
10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35

## Querying Media Assets

You can query media assets by condition such as the media type, date, or album name.

To 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.

To 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.

**Prerequisites**

- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.READ_MEDIA**.

### Querying Media Assets with the Specified Media Type

The following describes how to obtain images.

**How to Develop**

To specify the media type as the retrieval condition, set **selections** to **FileKey.MEDIA_TYPE**.

To specify the image as the media type, set **selectionArgs** to **MediaType.IMAGE**.

```ts
async function example() {
G
Gloria 已提交
36 37 38 39 40 41 42 43 44
  let fileKeyObj = mediaLibrary.FileKey;
  let fileType = mediaLibrary.MediaType.IMAGE;
  let option = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [fileType.toString()],
  };
  const context = getContext(this);
  let media = mediaLibrary.getMediaLibrary(context);
  const fetchFileResult = await media.getFileAssets(option);
G
Gloria 已提交
45
  fetchFileResult.getFirstObject().then(async (fileAsset) => {
G
Gloria 已提交
46 47
    console.log('getFirstObject.displayName : ' + fileAsset.displayName);
    for (let i = 1; i < fetchFileResult.getCount(); i++) {
G
Gloria 已提交
48 49
      let fileAsset = await fetchFileResult.getNextObject();
      console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
G
Gloria 已提交
50 51 52 53
    }
  }).catch((err) => {
    console.error('Failed to get first object: ' + err);
  });
G
Gloria 已提交
54 55 56 57 58
}
```

### Querying Media Assets with the Specified Date

G
Gloria 已提交
59
The 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.
G
Gloria 已提交
60 61 62 63 64 65 66

To specify the date when the files are added as the retrieval condition, set **selections** to **FileKey.DATE_ADDED**.

To specify the date 2022-8-5, set **selectionArgs** to **2022-8-5**.

```ts
async function example() {
G
Gloria 已提交
67 68 69 70 71 72 73 74
  let fileKeyObj = mediaLibrary.FileKey;
  let option = {
    selections: fileKeyObj.DATE_ADDED + '> ?',
    selectionArgs: ['2022-8-5'],
  };
  const context = getContext(this);
  let media = mediaLibrary.getMediaLibrary(context);
  const fetchFileResult = await media.getFileAssets(option);
G
Gloria 已提交
75
  fetchFileResult.getFirstObject().then(async (fileAsset) => {
G
Gloria 已提交
76 77
    console.info('getFirstObject.displayName : ' + fileAsset.displayName);
    for (let i = 1; i < fetchFileResult.getCount(); i++) {
G
Gloria 已提交
78 79
      let fileAsset = await fetchFileResult.getNextObject();
      console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
G
Gloria 已提交
80 81 82 83
    }
  }).catch((err) => {
    console.error('Failed to get first object: ' + err);
  });
G
Gloria 已提交
84 85 86 87 88 89 90 91 92 93 94
}
```

### Querying Media Assets and Sorting Them

The 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.

To sort files in descending order by the date when they are added, set **order** to **FileKey.DATE_ADDED + " DESC"**.

```ts
async function example() {
G
Gloria 已提交
95 96 97 98 99 100 101 102 103 104
  let fileKeyObj = mediaLibrary.FileKey;
  let fileType = mediaLibrary.MediaType.IMAGE;
  let option = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [fileType.toString()],
    order: fileKeyObj.DATE_ADDED + " DESC",
  };
  const context = getContext(this);
  let media = mediaLibrary.getMediaLibrary(context);
  const fetchFileResult = await media.getFileAssets(option);
G
Gloria 已提交
105
  fetchFileResult.getFirstObject().then(async (fileAsset) => {
G
Gloria 已提交
106 107
    console.info('getFirstObject.displayName : ' + fileAsset.displayName);
    for (let i = 1; i < fetchFileResult.getCount(); i++) {
G
Gloria 已提交
108 109
      let fileAsset = await fetchFileResult.getNextObject();
      console.info('fileAsset.displayName ' + i + ': ' + fileAsset.displayName);
G
Gloria 已提交
110 111 112 113
    }
  }).catch((err) => {
    console.error('Failed to get first object: ' + err);
  });
G
Gloria 已提交
114 115 116 117 118 119 120 121 122 123 124 125 126
}
```

### Querying Media Assets with the Specified Album Name

The following describes how to query media assets in **myAlbum**.

To specify the album name as the retrieval condition, set **selections** to **FileKey.ALBUM_NAME**.

To specify the album name **'myAlbum'**, set **selectionArgs** to **'myAlbum'**.

```ts
async function example() {
G
Gloria 已提交
127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143
  let fileKeyObj = mediaLibrary.FileKey;
  let option = {
    selections: fileKeyObj.ALBUM_NAME + '= ?',
    selectionArgs: ['myAlbum'],
  };
  const context = getContext(this);
  let media = mediaLibrary.getMediaLibrary(context);
  const fetchFileResult = await media.getFileAssets(option);
  if (albumList.length > 0) {
    fetchFileResult.getFirstObject().then((album) => {
      console.info('getFirstObject.displayName : ' + album.albumName);
    }).catch((err) => {
      console.error('Failed to get first object: ' + err);
    });
  } else {
    console.info('getAlbum list is: 0');
  }
G
Gloria 已提交
144 145 146 147 148 149
}
```

## Obtaining Images and Videos in an Album

You can obtain media assets in an album in either of the following ways:
J
Jiefeng Li 已提交
150
- Call [MediaLibrary.getFileAssets](../reference/apis/js-apis-medialibrary.md#getfileassets7-1) with an album specified, as described in [Querying Media Assets with the Specified Album Name](#querying-media-assets-with-the-specified-album-name).
G
Gloria 已提交
151 152 153 154 155 156 157 158 159 160 161 162 163
- 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.

**Prerequisites**

- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.READ_MEDIA**.

**How to Develop**

The following describes how to obtain videos in an album named **New Album 1**.

1. Create a retrieval condition for obtaining the target **Album** instance.

G
Gloria 已提交
164 165 166 167 168 169 170
```ts
let fileKeyObj = mediaLibrary.FileKey;
let AlbumNoArgsFetchOp = {
  selections: fileKeyObj.ALBUM_NAME + '= ?',
  selectionArgs:['New Album 1']
}
```
G
Gloria 已提交
171 172 173

2. Create a retrieval condition for obtaining videos in the target album.

G
Gloria 已提交
174 175 176 177 178 179 180 181
```ts
let fileKeyObj = mediaLibrary.FileKey;
let videoType = mediaLibrary.MediaType.VIDEO;
let videoFetchOp  = {
  selections: fileKeyObj.MEDIA_TYPE + '= ?',
  selectionArgs: [videoType.toString()],
}
```
G
Gloria 已提交
182 183 184 185 186 187 188

3. Call **Album.getFileAssets** to obtain the videos in the target album.

Complete sample code:

```ts
async function getCameraImagePromise() {
G
Gloria 已提交
189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210
  const context = getContext(this);
  let media = mediaLibrary.getMediaLibrary(context);
  let fileKeyObj = mediaLibrary.FileKey;
  let videoType = mediaLibrary.MediaType.VIDEO;
  let videoFetchOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [videoType.toString()],
  }
  let AlbumNoArgsFetchOp = {
    selections: fileKeyObj.ALBUM_NAME + '= ?',
    selectionArgs:['New Album 1']
  }

  let albumList = await media.getAlbums(AlbumNoArgsFetchOp);
  if (albumList.length > 0) {
    const album = albumList[0];
    let fetchFileResult = await album.getFileAssets(videoFetchOp);
    let count = fetchFileResult.getCount();
    console.info("get mediaLibrary VIDEO number", count);
  } else {
    console.info('getAlbum list is: 0');
  }
G
Gloria 已提交
211 212 213 214 215
}
```

## Obtaining the Thumbnail of an Image or a Video

G
Gloria 已提交
216
You 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.
G
Gloria 已提交
217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235

**Prerequisites**

- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.READ_MEDIA**.

### Obtaining the Thumbnail of an Image

The following describes how to obtain the thumbnail (size: 720 x 720) of the first image in the album.

**How to Develop**

1. Create a retrieval condition for obtaining images in the target album.
2. Call **getFileAssets** to obtain the images in the target album.
3. Call **getFirstObject** to obtain the first image among all the images obtained.
4. Call **getThumbnail** to obtain the thumbnail of the first image.

```ts
async function getFirstThumbnailPromise() {
G
Gloria 已提交
236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261
  const context = getContext(this);
  let media = mediaLibrary.getMediaLibrary(context);
  let fileKeyObj = mediaLibrary.FileKey;
  let imageType = mediaLibrary.MediaType.IMAGE;
  let imagesFetchOp = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [imageType.toString()],
  }

  let size = { width: 720, height: 720 };
  const fetchFileResult = await media.getFileAssets(imagesFetchOp);
  if (fetchFileResult === undefined) {
    console.error("get image failed with error");
    return;
  } else {
    const asset = await fetchFileResult.getFirstObject();
    asset.getThumbnail(size).then((pixelMap) => {
      pixelMap.getImageInfo().then((info) => {
        console.info('get Thumbnail info: ' + "width: " + info.size.width + " height: " + info.size.height);
      }).catch((err) => {
        console.error("getImageInfo failed with error: " + err);
      });
    }).catch((err) => {
      console.error("getImageInfo failed with error: " + err);
    });
  }
G
Gloria 已提交
262 263 264 265 266 267 268 269 270 271 272
}
```

## Creating a Media Asset

You can call [MediaLibrary.createAsset](../reference/apis/js-apis-medialibrary.md#createasset8-1) to create a media asset.

**Prerequisites**

- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**.
G
Gloria 已提交
273
- [You have obtained a public directory](medialibrary-filepath-guidelines.md).
G
Gloria 已提交
274 275 276 277 278

The following describes how to create a file of the **MediaType.FILE** type.

```ts
async function example() {
G
Gloria 已提交
279 280 281 282 283 284 285 286 287 288
  let mediaType = mediaLibrary.MediaType.FILE;
  let DIR_DOCUMENTS = mediaLibrary.DirectoryType.DIR_DOCUMENTS;
  const context = getContext(this);
  let media = mediaLibrary.getMediaLibrary(context);
  const path = await media.getPublicDirectory(DIR_DOCUMENTS);
  media.createAsset(mediaType, "testFile.text", path).then((asset) => {
    console.info("createAsset successfully:"+ JSON.stringify(asset));
  }).catch((err) => {
    console.error("createAsset failed with error: " + err);
  });
G
Gloria 已提交
289 290 291 292 293 294 295
}
```

## Moving a Media Asset to the Recycle Bin

You can use [FileAsset.trash](../reference/apis/js-apis-medialibrary.md#trash8) to move a media asset to the recycle bin.

G
Gloria 已提交
296
By 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**.
G
Gloria 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

**Prerequisites**

- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**.

The following describes how to move the first file in the result set to the recycle bin.

**How to Develop**

1. Create a retrieval condition for obtaining images in the target album.
2. Call **getFileAssets** to obtain the images in the target album.
3. Call **getFirstObject** to obtain the first image among all the images obtained.
4. Call **trash** to move the first image to the recycle bin.

```ts
async function example() {
G
Gloria 已提交
314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333
  let fileKeyObj = mediaLibrary.FileKey;
  let fileType = mediaLibrary.MediaType.FILE;
  let option = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [fileType.toString()],
  };
  const context = getContext(this);
  let media = mediaLibrary.getMediaLibrary(context);
  const fetchFileResult = await media.getFileAssets(option);
  let asset = await fetchFileResult.getFirstObject();
  if (asset === undefined) {
    console.error('asset not exist');
    return;
  }
  // Void callback.
  asset.trash(true).then(() => {
    console.info("trash successfully");
  }).catch((err) => {
    console.error("trash failed with error: " + err);
  });
G
Gloria 已提交
334 335 336 337 338
}
```

## Renaming a Media Asset

G
Gloria 已提交
339
To 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).
G
Gloria 已提交
340

G
Gloria 已提交
341
Before renaming a file, you must obtain the file, for example, by calling [FetchFileResult](../reference/apis/js-apis-medialibrary.md#fetchfileresult7).
G
Gloria 已提交
342 343 344 345 346 347

**Prerequisites**

- You have obtained a **MediaLibrary** instance.
- You have granted the permission **ohos.permission.WRITE_MEDIA**.

G
Gloria 已提交
348
The following describes how to rename the first file in the result set as **newImage.jpg**.
G
Gloria 已提交
349 350 351 352 353 354 355

**How to Develop**

1. Create a retrieval condition for obtaining images in the target album.
2. Call **getFileAssets** to obtain the images in the target album.
3. Call **getFirstObject** to obtain the first image among all the images obtained.
4. Rename the image as **newImage.jpg**.
G
Gloria 已提交
356
5. Call **FileAsset.commitModify** to commit the modification to the database.
G
Gloria 已提交
357 358 359

```ts
async function example() {
G
Gloria 已提交
360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378
  let fileKeyObj = mediaLibrary.FileKey;
  let fileType = mediaLibrary.MediaType.IMAGE;
  let option = {
    selections: fileKeyObj.MEDIA_TYPE + '= ?',
    selectionArgs: [fileType.toString()],
  };
  const context = getContext(this);
  let media = mediaLibrary.getMediaLibrary(context);
  const fetchFileResult = await media.getFileAssets(option);
  let asset = await fetchFileResult.getFirstObject();
  if (asset === undefined) {
    console.error('asset not exist');
    return;
  }
  asset.displayName = 'newImage.jpg';
  // Void callback.
  asset.commitModify((err) => {
    if (err) {
      console.error('fileRename Failed ');
379
      return;
G
Gloria 已提交
380
    }
G
Gloria 已提交
381 382
    console.info('fileRename successful.');
  });
G
Gloria 已提交
383 384
}
```