RecentPhotoComponent is a UI component that allows an application to access the latest image/video in the user directory without the required permission. This component grants the application only the read permission.
The following figure shows the UI effect.

Import modules.
import { BaseItemInfo } from '@ohos.file.PhotoPickerComponent';
import {
PhotoSource,
RecentPhotoComponent,
RecentPhotoOptions,
photoAccessHelper
} from '@kit.MediaLibraryKit'; Create a RecentPhotoOptions instance.
You can use RecentPhotoOptions to set the time period, file types, and source of the file to display. For details, see RecentPhotoOptions.
// Initialize RecentPhotoComponent. recentPhotoOptions: RecentPhotoOptions = new RecentPhotoOptions();
Initialize the RecentPhotoOptions instance.
// Set the data type. IMAGE_VIDEO_TYPE (default value) indicates image and video; IMAGE_TYPE indicates image; VIDEO_TYPE indicates video; MOVING_PHOTO_IMAGE_TYPE indicates moving photo. this.recentPhotoOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE; // Set the time period of the latest image/video, in seconds. The value 0 means there is no time limit. this.recentPhotoOptions.period = 0; // Set the resource source. The value ALL indicates all resources; CAMERA indicates resources related to the camera; SCREENSHOT indicates screenshots. this.recentPhotoOptions.photoSource = PhotoSource.ALL;
Create a RecentPhotoComponent.
RecentPhotoComponent({
// Set recentPhotoOptions.
recentPhotoOptions: this.recentPhotoOptions,
/**
* Callback to be invoked when the latest image/video is selected.
* BaseItemInfo(uri, mimeType, width, height, size, duration)
* If true is returned, the URL is granted with the permission and the latest image/video is displayed.
*/
onRecentPhotoClick: (recentPhotoInfo: BaseItemInfo): boolean => this.onRecentPhotoClick(recentPhotoInfo),
// Check whether the latest resource exists.
onRecentPhotoCheckResult: (recentPhotoExists: boolean) => this.onReceiveCheckResult(recentPhotoExists),
}) Implement related callbacks.
Implement the onReceiveCheckResult callback to check whether the latest image/video exists. The logic for whether to display the latest image/video is executed only when true is returned.
Implement the onRecentPhotoClick callback to return the image/video information in BaseItemInfo.
// The URI is granted with the permission only when the return value is true.
private onRecentPhotoClick(recentPhotoInfo: BaseItemInfo): boolean {
if (!recentPhotoInfo) {
return false;
}
return true;
}
private onReceiveCheckResult(recentPhotoExists: boolean): void {
if (!recentPhotoExists) {
console.info('not exist recent photo');
}
// If the latest image/video exists, implement the subsequent service logic, for example, whether to display RecentPhotoComponent.
}