1# Accessing and Managing Moving Photos
2
3A moving photo is a photo form that combines an image and a video, empowering a static image with dynamic video effect. It helps users capture dynamic moment and improves the fault tolerance rate of photographing.
4
5The media library provides the capabilities of accessing and managing moving photo assets, including:
6
7- [Saves Moving Photo Assets using SaveButton](#saves-moving-photo-assets)
8- [Obtaining a Moving Photo Object](#obtaining-a-moving-photo-object)
9- [Playing Moving Photos with MovingPhotoView](movingphotoview-guidelines.md)
10- [Reading Moving Photo Assets](#reading-moving-photo-assets)
11
12Camera Kit provides the capability of taking moving photos. For details, see [Moving Photos](../camera/camera-moving-photo.md).
13
14## Saves Moving Photo Assets
15
16Use the **SaveButton** security component to save the assets (image and video) of a moving photo.
17
18With the **SaveButton** security component, the application does not need the ohos.permission.WRITE_IMAGEVIDEO permission. When the user taps the button embedded with the **SaveButton** security component, the application obtains the temporary permission to save the assets to the specified media library directory.
19
20For details, see [SaveButton](../../reference/apis-arkui/arkui-ts/ts-security-components-savebutton.md).
21
22**How to Develop**
23
241. Set the properties of the **SaveButton** security component.
252. Create a button with **SaveButton**.
263. Call [MediaAssetChangeRequest.createAssetRequest](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#createassetrequest11) to create an asset change request with **PhotoSubtype** set to **MOVING_PHOTO**.
274. Call [MediaAssetChangeRequest.addResource](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#addresource11) to set the image and video of the moving photo.
28
29   In the following example, the image and video of the moving photo are specified by **fileUri** of the [application file](../../file-management/app-file-access.md) in the application sandbox.
30
31   You can also specify the assets in **ArrayBuffer**. For details, see [MediaAssetChangeRequest.addResource(type: ResourceType, data: ArrayBuffer)](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#addresource11-1).
32
335. Call [PhotoAccessHelper.applyChanges](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#applychanges11) to apply changes for the moving photo.
34
35```ts
36import { photoAccessHelper } from '@kit.MediaLibraryKit';
37
38@Entry
39@Component
40struct Index {
41  @State message: string = 'Hello World'
42  @State saveButtonOptions: SaveButtonOptions = {
43    icon: SaveIconStyle.FULL_FILLED,
44    text: SaveDescription.SAVE_IMAGE,
45    buttonType: ButtonType.Capsule
46  } // Set properties of SaveButton.
47
48  build() {
49    Row() {
50      Column() {
51        Text(this.message)
52          .fontSize(50)
53          .fontWeight(FontWeight.Bold)
54        SaveButton(this.saveButtonOptions) // Create a button with SaveButton.
55          .onClick(async (event, result: SaveButtonOnClickResult) => {
56             if (result == SaveButtonOnClickResult.SUCCESS) {
57               try {
58                 let context = getContext();
59                 let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
60                 // Ensure that the assets specified by imageFileUri and videoFileUri exist. imageFileUri and videoFileUri specify the image and video of the moving photo to create.
61                 let imageFileUri = 'file://com.example.temptest/data/storage/el2/base/haps/entry/files/create_moving_photo.jpg';
62                 let videoFileUri = 'file://com.example.temptest/data/storage/el2/base/haps/entry/files/create_moving_photo.mp4';
63                 let assetChangeRequest: photoAccessHelper.MediaAssetChangeRequest = photoAccessHelper.MediaAssetChangeRequest.createAssetRequest(context, photoAccessHelper.PhotoType.IMAGE, "jpg", {
64                  title: "moving_photo",
65                  subtype: photoAccessHelper.PhotoSubtype.MOVING_PHOTO
66                 });
67                 assetChangeRequest.addResource(photoAccessHelper.ResourceType.IMAGE_RESOURCE, imageFileUri);
68                 assetChangeRequest.addResource(photoAccessHelper.ResourceType.VIDEO_RESOURCE, videoFileUri);
69                 await phAccessHelper.applyChanges(assetChangeRequest);
70                 console.info('create moving photo successfully, uri: ' + assetChangeRequest.getAsset().uri);
71               } catch (err) {
72                 console.error(`create moving photo failed with error: ${err.code}, ${err.message}`);
73               }
74             } else {
75               console.error('SaveButtonOnClickResult create moving photo failed');
76             }
77          })
78      }
79      .width('100%')
80    }
81    .height('100%')
82  }
83}
84```
85
86## Obtaining a Moving Photo Object
87
88- Use **Picker** to obtain a moving photo object from the media library.
89
90- Create a local moving photo object of the application by passing **fileUri** of an [application file](../../file-management/app-file-access.md) in the application sandbox.
91
92After obtaining a moving photo object, you can use [MovingPhotoView](movingphotoview-guidelines.md) to play it.
93
94### Obtaining a Moving Photo Object from the Media Library
95
961. Select the [URI of a media file](../../file-management/user-file-uri-intro.md#media-file-uri) by using **Picker**.
972. Call [PhotoAccessHelper.getAssets](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#getassets-1) and [FetchResult.getFirstObject](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#getfirstobject-1) to obtain the photo asset corresponding to the URI.
983. Call [MediaAssetManager.requestMovingPhoto](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#requestmovingphoto12) to obtain the moving photo object.
99
100```ts
101import { photoAccessHelper } from '@kit.MediaLibraryKit';
102import { dataSharePredicates } from '@kit.ArkData';
103let context = getContext(this);
104let phAccessHelper = photoAccessHelper.getPhotoAccessHelper(context);
105
106async function example() {
107  try {
108    // Use Picker to select the URI of the moving photo.
109    let photoSelectOptions = new photoAccessHelper.PhotoSelectOptions();
110    photoSelectOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.MOVING_PHOTO_IMAGE_TYPE;
111    photoSelectOptions.maxSelectNumber = 9;
112    let photoViewPicker = new photoAccessHelper.PhotoViewPicker();
113    let photoSelectResult = await photoViewPicker.select(photoSelectOptions);
114    let uris = photoSelectResult.photoUris;
115    for (let i = 0; i < uris.length; i++) {
116      // Obtain the photo asset corresponding to the URI.
117      let predicates: dataSharePredicates.DataSharePredicates = new dataSharePredicates.DataSharePredicates();
118      predicates.equalTo(photoAccessHelper.PhotoKeys.URI, uris[i]);
119      let fetchOption: photoAccessHelper.FetchOptions = {
120        fetchColumns: [],
121        predicates: predicates
122      };
123      let fetchResult: photoAccessHelper.FetchResult<photoAccessHelper.PhotoAsset> = await phAccessHelper.getAssets(fetchOption);
124      let photoAsset: photoAccessHelper.PhotoAsset = await fetchResult.getFirstObject();
125      // Obtain the moving photo object corresponding to the photo asset.
126      await photoAccessHelper.MediaAssetManager.requestMovingPhoto(context, photoAsset, {
127        deliveryMode: photoAccessHelper.DeliveryMode.FAST_MODE
128      }, {
129        async onDataPrepared(movingPhoto: photoAccessHelper.MovingPhoto) {
130          if (movingPhoto !== undefined) {
131            // Customize the logic for processing the moving photo.
132            console.info('request moving photo successfully, uri: ' + movingPhoto.getUri());
133          }
134        }
135      })
136    }
137  } catch (err) {
138    console.error(`request moving photo failed with error: ${err.code}, ${err.message}`);
139  }
140}
141```
142
143### Obtaining a Moving Photo object in an Application Sandbox Directory
144
145Call [MediaAssetManager.loadMovingPhoto](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#loadmovingphoto12) to load the moving photo object in the application sandbox directory.
146
147```ts
148import { photoAccessHelper } from '@kit.MediaLibraryKit';
149let context = getContext(this);
150
151async function example() {
152  try {
153    let imageFileUri = 'file://com.example.temptest/data/storage/el2/base/haps/entry/files/local_moving_photo.jpg';
154    let videoFileUri = 'file://com.example.temptest/data/storage/el2/base/haps/entry/files/local_moving_photo.mp4';
155    let movingPhoto = await photoAccessHelper.MediaAssetManager.loadMovingPhoto(context, imageFileUri, videoFileUri);
156    console.info('load moving photo successfully');
157  } catch (err) {
158    console.error(`load moving photo failed with error: ${err.code}, ${err.message}`);
159  }
160}
161```
162
163## Reading Moving Photo Assets
164
165Call [MovingPhoto.requestContent](../../reference/apis-media-library-kit/js-apis-photoAccessHelper.md#requestcontent12) to export the image and video of a moving photo to the application sandbox directory or read the image and video data from **ArrayBuffer**.
166
167```ts
168import { photoAccessHelper } from '@kit.MediaLibraryKit';
169
170async function example(movingPhoto: photoAccessHelper.MovingPhoto) {
171  try {
172    let imageFileUri = 'file://com.example.temptest/data/storage/el2/base/haps/entry/files/request_moving_photo.jpg';
173    let videoFileUri = 'file://com.example.temptest/data/storage/el2/base/haps/entry/files/request_moving_photo.mp4';
174    await movingPhoto.requestContent(imageFileUri, videoFileUri); // Export the image and video of the moving photo to the application sandbox directory.
175    let imageData = await movingPhoto.requestContent(photoAccessHelper.ResourceType.IMAGE_RESOURCE); // Read ArrayBuffer to obtain the image data.
176    let videoData = await movingPhoto.requestContent(photoAccessHelper.ResourceType.VIDEO_RESOURCE); // Read ArrayBuffer to obtain the video data.
177  } catch (err) {
178    console.error(`request content of moving photo failed with error: ${err.code}, ${err.message}`);
179  }
180}
181```
182