• Home
  • Line#
  • Scopes#
  • Navigate#
  • Raw
  • Download
1# Saving Media Assets
2
3When users wish to save images, videos, or similar files to Gallery, it is not necessary for the application to request the ohos.permission.WRITE_IMAGEVIDEO permission. Instead, the application can use the [SaveButton](#creating-a-media-asset-using-savebutton) or [authorization pop-up](#saving-a-media-asset-using-an-authorization-pop-up) to save the media assets to Gallery.
4
5## Obtaining Supported Resource Formats for Saving
6
7The following describes how to obtain image resource formats that can be saved.
8
9**How to Develop**
10
11Call [phAccessHelper.getSupportedPhotoFormats](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#getsupportedphotoformats18) to obtain the supported image formats that can be saved.
12
13```ts
14import photoAccessHelper from '@ohos.file.photoAccessHelper';
15
16let context = getContext(this);
17let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
18@Entry
19@Component
20
21struct Index {
22  @State outputText: string = 'Supported formats:\n';
23
24  async function example(){
25    try {
26      this.outputText = 'Supported formats:\n';
27      // The value 1 means the supported image formats, and 2 means the supported video formats.
28      let imageFormat  = await phAccessHelper.getSupportedPhotoFormats(1);
29      let result = "";
30      for (let i = 0; i < imageFormat.length; i++) {
31        result += imageFormat[i];
32        if (i !== imageFormat.length - 1) {
33          result += ', ';
34        }
35      }
36      this.outputText += result;
37      console.info('getSupportedPhotoFormats success, data is ' + outputText);
38    } catch (error) {
39      console.error('getSupportedPhotoFormats failed, errCode is', error);
40    }
41  }
42```
43
44## Creating a Media Asset Using SaveButton
45
46For details about the **SaveButton** component, see [SaveButton](../../reference/apis-arkui/arkui-ts/ts-security-components-savebutton.md).
47
48This following walks you through on how to create an image using the **SaveButton** security component.
49
50**How to Develop**
51
521. Set the attributes of the security component.
532. Create a button with the security component.
543. Use [MediaAssetChangeRequest.createImageAssetRequest](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#createimageassetrequest11) and [PhotoAccessHelper.applyChanges](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#applychanges11) to create an image asset.
55
56```ts
57import { photoAccessHelper } from '@kit.MediaLibraryKit';
58
59@Entry
60@Component
61struct Index {
62    saveButtonOptions: SaveButtonOptions = {
63    icon: SaveIconStyle.FULL_FILLED,
64    text: SaveDescription.SAVE_IMAGE,
65    buttonType: ButtonType.Capsule
66  } // Set properties of SaveButton.
67
68  build() {
69    Row() {
70      Column() {
71        SaveButton(this.saveButtonOptions) // Create a button with SaveButton.
72          .onClick(async (event, result: SaveButtonOnClickResult) => {
73             if (result == SaveButtonOnClickResult.SUCCESS) {
74               try {
75                 let context = getContext();
76                 let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
77                 // Ensure that the asset specified by fileUri exists.
78                 let fileUri = 'file://com.example.temptest/data/storage/el2/base/haps/entry/files/test.jpg';
79                 let assetChangeRequest: photoAccessHelper.MediaAssetChangeRequest = photoAccessHelper.MediaAssetChangeRequest.createImageAssetRequest(context, fileUri);
80                 await phAccessHelper.applyChanges(assetChangeRequest);
81                 console.info('createAsset successfully, uri: ' + assetChangeRequest.getAsset().uri);
82               } catch (err) {
83                 console.error(`create asset failed with error: ${err.code}, ${err.message}`);
84               }
85             } else {
86               console.error('SaveButtonOnClickResult create asset failed');
87             }
88          })
89      }
90      .width('100%')
91    }
92    .height('100%')
93  }
94}
95```
96
97In addition to specifying the asset in the application sandbox directory using **fileUri**, you can add the asset using ArrayBuffer. For details, see the [addResource](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#addresource11-1).
98
99## Saving a Media Asset Using an Authorization Pop-Up
100
101This following walks you through on how to save an image using an authorization pop-up.
102
103**How to Develop**
104
1051. Specify the URI of the [application file](../../file-management/app-file-access.md) in the application sandbox.
1062. Set parameters such as the file name extension, image file type, title (optional) and image subtype (optional) of the image to save.
1073. Call [showAssetsCreationDialog](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#showassetscreationdialog12) to obtain the target [media file URI](../../file-management/user-file-uri-intro.md#media-file-uri) through an authorization pop-up.
1084. Write the image content from the application sandbox directory to the file specified by the target URI in the media library.
109
110```ts
111import { photoAccessHelper } from '@kit.MediaLibraryKit';
112import { fileIo } from '@kit.CoreFileKit';
113
114let context = getContext(this);
115let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
116
117async function example() {
118  try {
119    // Specify the URI of the image in the application sandbox directory to be saved.
120    let srcFileUri = 'file://com.example.temptest/data/storage/el2/base/haps/entry/files/test.jpg';
121    let srcFileUris: Array<string> = [
122      srcFileUri
123    ];
124    // Set parameters such as the file name extension, image file type, title (optional) and image subtype (optional) of the image to save.
125    let photoCreationConfigs: Array<photoAccessHelper.PhotoCreationConfig> = [
126      {
127        title: 'test', // This parameter is optional.
128        fileNameExtension: 'jpg',
129        photoType: photoAccessHelper.PhotoType.IMAGE,
130        subtype: photoAccessHelper.PhotoSubtype.DEFAULT, // This parameter is optional.
131      }
132    ];
133    // Obtain the target URI in the media library based on pop-up authorization.
134    let desFileUris: Array<string> = await phAccessHelper.showAssetsCreationDialog(srcFileUris, photoCreationConfigs);
135    // Write the image content from the application sandbox directory to the file specified by the target URI in the media library.
136    let desFile: fileIo.File = await fileIo.open(desFileUris[0], fileIo.OpenMode.WRITE_ONLY);
137    let srcFile: fileIo.File = await fileIo.open(srcFileUri, fileIo.OpenMode.READ_ONLY);
138    await fileIo.copyFile(srcFile.fd, desFile.fd);
139    fileIo.closeSync(srcFile);
140    fileIo.closeSync(desFile);
141    console.info('create asset by dialog successfully');
142  } catch (err) {
143    console.error(`failed to create asset by dialog successfully errCode is: ${err.code}, ${err.message}`);
144  }
145}
146```
147