一、替换PhotoPicker中显示的图片/视频

应用可获得用户从Picker选择的图片、视频的访问权限,读取图片、视频后进行编辑、修改。完成编辑修改后的图片/视频缓存到应用沙箱后,可调用本API,将编辑结果文件发送给PhotoPicker,并指定替换显示的原图。Picker根据指定将接收的编辑结果文件替换原图片进行显示。

效果如图所示

替换前

HarmonyOS:使用PickerController将编辑后的图片替换原图_HarmonyOS

替换后

HarmonyOS:使用PickerController将编辑后的图片替换原图_HarmonyOS NEXT_02

日志图

HarmonyOS:使用PickerController将编辑后的图片替换原图_HarmonyOS NEXT_03

1.1 开发步骤
1.1.1 导入选择器模块和文件管理模块
import { PickerController } from '@ohos.file.PhotoPickerComponent';
import { fileUri } from '@kit.CoreFileKit';
  • 1.
  • 2.
1.1.2 创建参数列表
@State pickerController: PickerController = new PickerController();
@State originUrl: string = ''; // 原图URI
@State replaceUrl: string = ''; // 原图编辑后的沙箱URI
  • 1.
  • 2.
  • 3.
1.1.3 调用replacePhotoPickerPreview()替换图片/视频

replacePhotoPickerPreview
replacePhotoPickerPreview(originalUri: string, newUri: string, callback: AsyncCallback): void
应用可通过该接口,将photoPicker中用户勾选的图片替换为应用后期编辑修改后的图片。
元服务API:从API version 15开始,该接口支持在元服务中使用。
系统能力:SystemCapability.FileManagement.PhotoAccessHelper.Core

参数:

参数名

类型

必填

说明

originalUri

string

原uri,将会被替换掉的uri。

newUri

boolean

新uri,即替换后的uri。基于originalUri修改后期望在photoPicker上替换originalUri显示的,暂存在应用沙箱的图片/视频uri。

callback

AsyncCallback\

调用接口完成替换后的回调。

调用示例

this.pickerController.replacePhotoPickerPreview(this.originUrl, this.replaceUrl, (a, b) => {
  console.log("hello this.pickerController.replaceUrl code :" +  err.code)
})
  • 1.
  • 2.
  • 3.
1.2 完整示例
import {
  ClickType,
  ItemInfo,
  ItemType,
  PhotoPickerComponent,
  PickerController,
  PickerOptions,
  ReminderMode,
  SelectMode
} from '@ohos.file.PhotoPickerComponent';
import { fileUri } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';



@Entry
@Component
struct TestPickerControllerEdit {
  @State pickerController: PickerController = new PickerController();
  @State originUrl: string = '';// 原图
  @State replaceUrl: string = '';// 原图编辑后的沙箱 url
  // 组件初始化时设置参数信息
  pickerOptions: PickerOptions = new PickerOptions();
  // 组件初始化完成后,可控制组件部分行为

  // 已选择的图片
  @State selectUris: Array<string> = new Array<string>();
  //目前选择的图片
  @State currentUri: string = '';

  context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext;


  // 资源被选中回调,返回资源的信息,以及选中方式
  private onItemClicked(itemInfo: ItemInfo, clickType: ClickType): boolean {
    if (!itemInfo) {
      return false;
    }
    let type: ItemType | undefined = itemInfo.itemType;
    let uri: string | undefined = itemInfo.uri;
    if (type === ItemType.CAMERA) {
      // 点击相机item
      return true; // 返回true则拉起系统相机,若应用需要自行处理则返回false。
    } else {
      if (clickType === ClickType.SELECTED) {
        // 应用做自己的业务处理
        if (uri) {
          this.originUrl = uri.toString()
          this.selectUris.push(uri);
          this.pickerOptions.preselectedUris = [...this.selectUris];
        }
        return true; // 返回true则勾选,否则则不响应勾选。
      } else {
        if (uri) {
          this.originUrl = ''
          this.selectUris = this.selectUris.filter((item: string) => {
            return item != uri;
          });
          this.pickerOptions.preselectedUris = [...this.selectUris];
        }
      }
      return true;
    }
  }

  aboutToDisappear(): void {
    // 设置picker宫格页数据类型
    this.pickerOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE // 图片和照片都显示;
    // 最大选择数量
    this.pickerOptions.maxSelectNumber = 1;
    // 超出最大选择数量时
    this.pickerOptions.maxSelectedReminderMode = ReminderMode.TOAST;
    // 是否展示搜索框,默认false
    this.pickerOptions.isSearchSupported = true;
    // 是否支持拍照,默认false
    this.pickerOptions.isPhotoTakingSupported = true;

    // 选择模式, SINGLE_SELECT	0	单选模式; MULTI_SELECT	1	多选模式
    this.pickerOptions.selectMode = SelectMode.SINGLE_SELECT
  }

  build() {
    Column({ space: 10 }) {
      Row({ space: 10 }) {
        if (this.originUrl) {
          Image(this.originUrl)
            .height(100)
            .width(100)
            .onClick(() => {

            })
            .borderWidth(1)
            .borderColor('red')
        }
        Button("replace url")
          .fontWeight(FontWeight.Medium)
          .fontSize(20)
          .onClick(() => {
            // console.log("context.filesDir 路径:", this.context.filesDir)
            // context.filesDir 路径: /data/storage/el2/base/haps/entry/files
            // 原图编辑后的沙箱 url
            // this.replaceUrl = fileUri.getUriFromPath(this.context.filesDir + "/screenshot_20250326_160329.jpg").toString();
            // 写死方便测试
            this.replaceUrl = 'file://media/Photo/29/IMG_1747625089_025/IMG_20250519_112309.jpg';
            this.pickerController.replacePhotoPickerPreview(this.originUrl, this.replaceUrl, (err, b) => {
              console.log("替换, 通过 this.pickerController.replaceUrl code :" +  err.code)
            })
          })
      }.margin({ top: 10 })

      PhotoPickerComponent({
        pickerOptions: this.pickerOptions,
        onItemClicked: (itemInfo: ItemInfo, clickType: ClickType): boolean => this.onItemClicked(itemInfo, clickType),
        pickerController: this.pickerController,
      })
    }
    .width('100%')
    .height('100%')
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 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.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
二、将Picker上替换显示的图片/视频保存到图库

应用指定保存的文件,需在替换显示的范围内。应用调用API后,PhotoPicker将在Picker上成功替换显示的图片、视频保存到图库。确保保存的内容与替换显示的图片、视频一致。

效果如图所示保存前

HarmonyOS:使用PickerController将编辑后的图片替换原图_HarmonyOS NEXT_04

保存后

HarmonyOS:使用PickerController将编辑后的图片替换原图_HarmonyOS NEXT_05

日志图

HarmonyOS:使用PickerController将编辑后的图片替换原图_HarmonyOS_06

2.1 开发步骤
2.1.1 导入选择器模块和文件管理模块
import photoAccessHelper from '@ohos.file.photoAccessHelper';
import { PickerController, PickerOptions, SaveMode } from '@ohos.file.PhotoPickerComponent';
import { fileUri } from '@kit.CoreFileKit';
  • 1.
  • 2.
  • 3.
2.1.2 创建参数列表
@State pickerController: PickerController = new PickerController();
@State originUrl: string = ''; // 原图URI
@State replaceUrl: string = ''; // 原图编辑后的沙箱URI
  • 1.
  • 2.
  • 3.
2.1.3 调用saveTrustedPhotoAssets()保存图片/视频到图库
this.pickerController.saveTrustedPhotoAssets(this.replaceUris, (a, b) => {
  console.log("hello this.pickerController.save as new code a.code:" + a.code + ",a.message:" + a.message + ",res:" + b)
}, photoCreationConfigs, SaveMode.SAVE_AS); // SaveMode: SAVE_AS = 0(另存为),OVERWRITE = 1 (覆盖保存)
  • 1.
  • 2.
  • 3.

该接口使用依赖pickerController.replacePhotoPickerPreview,需要先执行pickerController.replacePhotoPickerPreview后才能执行pickerController.saveTrustedPhotoAssets。

2.2 完整示例
import {
  ClickType,
  ItemInfo,
  ItemType,
  PhotoPickerComponent,
  PickerController,
  PickerOptions,
  ReminderMode,
  SaveMode,
  SelectMode
} from '@ohos.file.PhotoPickerComponent';
import { fileUri } from '@kit.CoreFileKit';
import { common } from '@kit.AbilityKit';
import { photoAccessHelper } from '@kit.MediaLibraryKit';


@Entry
@Component
struct TestPickerControllerEdit {
  @State pickerController: PickerController = new PickerController();
  @State originUrl: string = ''; // 原图
  @State replaceUrl: string = ''; // 原图编辑后的沙箱 url
  // 组件初始化时设置参数信息
  pickerOptions: PickerOptions = new PickerOptions();
  // 组件初始化完成后,可控制组件部分行为

  // 已选择的图片
  @State selectUris: Array<string> = new Array<string>();
  //目前选择的图片
  @State currentUri: string = '';
  context: Context = this.getUIContext().getHostContext() as common.UIAbilityContext;

  // 资源被选中回调,返回资源的信息,以及选中方式
  private onItemClicked(itemInfo: ItemInfo, clickType: ClickType): boolean {
    if (!itemInfo) {
      return false;
    }
    let type: ItemType | undefined = itemInfo.itemType;
    let uri: string | undefined = itemInfo.uri;
    if (type === ItemType.CAMERA) {
      // 点击相机item
      return true; // 返回true则拉起系统相机,若应用需要自行处理则返回false。
    } else {
      if (clickType === ClickType.SELECTED) {
        // 应用做自己的业务处理
        if (uri) {
          this.originUrl = uri.toString()
          this.selectUris.push(uri);
          this.pickerOptions.preselectedUris = [...this.selectUris];
        }
        return true; // 返回true则勾选,否则则不响应勾选。
      } else {
        if (uri) {
          this.originUrl = ''
          this.selectUris = this.selectUris.filter((item: string) => {
            return item != uri;
          });
          this.pickerOptions.preselectedUris = [...this.selectUris];
        }
      }
      return true;
    }
  }

  aboutToDisappear(): void {
    // 设置picker宫格页数据类型
    this.pickerOptions.MIMEType = photoAccessHelper.PhotoViewMIMETypes.IMAGE_VIDEO_TYPE // 图片和照片都显示;
    // 最大选择数量
    this.pickerOptions.maxSelectNumber = 1;
    // 超出最大选择数量时
    this.pickerOptions.maxSelectedReminderMode = ReminderMode.TOAST;
    // 是否展示搜索框,默认false
    this.pickerOptions.isSearchSupported = true;
    // 是否支持拍照,默认false
    this.pickerOptions.isPhotoTakingSupported = true;

    // 选择模式, SINGLE_SELECT	0	单选模式; MULTI_SELECT	1	多选模式
    this.pickerOptions.selectMode = SelectMode.SINGLE_SELECT
  }

  build() {
    Column({ space: 10 }) {
      Row({ space: 10 }) {
        if (this.originUrl) {
          Image(this.originUrl)
            .height(100)
            .width(100)
            .onClick(() => {

            })
            .borderWidth(1)
            .borderColor('red')
        }

        Column({ space: 10 }) {
          // 替换PhotoPicker中显示的图片/视频
          Button("replace url")
            .fontWeight(FontWeight.Medium)
            .fontSize(20)
            .onClick(() => {
              // console.log("context.filesDir 路径:", this.context.filesDir)
              // context.filesDir 路径: /data/storage/el2/base/haps/entry/files
              // 原图编辑后的沙箱 url
              // this.replaceUrl = fileUri.getUriFromPath(this.context.filesDir + "/screenshot_20250326_160329.jpg").toString();
              // 写死方便测试
              this.replaceUrl = 'file://media/Photo/29/IMG_1747625089_025/IMG_20250519_112309.jpg';
              this.pickerController.replacePhotoPickerPreview(this.originUrl, this.replaceUrl, (err, b) => {
                console.log("替换, 通过 this.pickerController.replaceUrl code :" + err.code)
              })
            })

          Button("save replace url")
            .fontWeight(FontWeight.Medium)
            .fontSize(20)
            .onClick(() => {
              // console.log("context.filesDir 路径:", this.context.filesDir)
              // context.filesDir 路径: /data/storage/el2/base/haps/entry/files
              // 原图编辑后的沙箱 url
              // this.replaceUrl = fileUri.getUriFromPath(this.context.filesDir + "/screenshot_20250326_160329.jpg").toString();
              // 写死方便测试
              this.replaceUrl = 'file://media/Photo/29/IMG_1747625089_025/IMG_20250519_112309.jpg';
              let photoCreationConfig: photoAccessHelper.PhotoCreationConfig = {
                title: 'test',
                fileNameExtension: 'jpg',
                photoType: photoAccessHelper.PhotoType.IMAGE,
                subtype: photoAccessHelper.PhotoSubtype.DEFAULT,
              };
              this.pickerController.saveTrustedPhotoAssets([this.replaceUrl], (err, arr) => {
                console.log("执行了 saveTrustedPhotoAssets  this.pickerController.save code res:" + err.code);
              }, [photoCreationConfig], SaveMode.SAVE_AS);
            })
        }
      }.margin({ top: 10 })

      PhotoPickerComponent({
        pickerOptions: this.pickerOptions,
        onItemClicked: (itemInfo: ItemInfo, clickType: ClickType): boolean => this.onItemClicked(itemInfo, clickType),
        pickerController: this.pickerController,
      })
    }
    .width('100%')
    .height('100%')
  }
}
  • 1.
  • 2.
  • 3.
  • 4.
  • 5.
  • 6.
  • 7.
  • 8.
  • 9.
  • 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.
  • 36.
  • 37.
  • 38.
  • 39.
  • 40.
  • 41.
  • 42.
  • 43.
  • 44.
  • 45.
  • 46.
  • 47.
  • 48.
  • 49.
  • 50.
  • 51.
  • 52.
  • 53.
  • 54.
  • 55.
  • 56.
  • 57.
  • 58.
  • 59.
  • 60.
  • 61.
  • 62.
  • 63.
  • 64.
  • 65.
  • 66.
  • 67.
  • 68.
  • 69.
  • 70.
  • 71.
  • 72.
  • 73.
  • 74.
  • 75.
  • 76.
  • 77.
  • 78.
  • 79.
  • 80.
  • 81.
  • 82.
  • 83.
  • 84.
  • 85.
  • 86.
  • 87.
  • 88.
  • 89.
  • 90.
  • 91.
  • 92.
  • 93.
  • 94.
  • 95.
  • 96.
  • 97.
  • 98.
  • 99.
  • 100.
  • 101.
  • 102.
  • 103.
  • 104.
  • 105.
  • 106.
  • 107.
  • 108.
  • 109.
  • 110.
  • 111.
  • 112.
  • 113.
  • 114.
  • 115.
  • 116.
  • 117.
  • 118.
  • 119.
  • 120.
  • 121.
  • 122.
  • 123.
  • 124.
  • 125.
  • 126.
  • 127.
  • 128.
  • 129.
  • 130.
  • 131.
  • 132.
  • 133.
  • 134.
  • 135.
  • 136.
  • 137.
  • 138.
  • 139.
  • 140.
  • 141.
  • 142.
  • 143.
  • 144.