在 Ionic 中,可以使用 Cordova 插件 cordova-plugin-photo-library 来保存图片到图库。要刷新媒体库,可以使用以下两种方法:

  1. 在保存图片后,使用 Cordova 插件 cordova-plugin-file 来删除图库中的缩略图文件,这将强制媒体库重新扫描图库并更新缩略图。
import { File } from '@ionic-native/file/ngx';

constructor(private file: File) {}

saveImageToGallery(imageData: string) {
  this.photoLibrary.saveImage(imageData, 'My Image').then(() => {
    // Successfully saved image to gallery
    this.file.removeFile(this.file.externalRootDirectory + '/DCIM/Camera', 'thumbnail_' + imageName).then(() => {
      // Thumbnail deleted, media library will refresh
    });
  });
}
  1. 直接使用 Cordova 插件 cordova-plugin-photo-library 中的 getLibrary 方法来获取媒体库,并手动刷新它。
import { PhotoLibrary } from '@ionic-native/photo-library/ngx';

constructor(private photoLibrary: PhotoLibrary) {}

saveImageToGallery(imageData: string) {
  this.photoLibrary.saveImage(imageData, 'My Image').then(() => {
    // Successfully saved image to gallery
    this.photoLibrary.getLibrary().subscribe({
      next: library => {
        // Media library refreshed
      },
      error: err => console.log('Error getting library', err)
    });
  });
}

注意:在第二种方法中,媒体库仅在更新时刷新,并非每次调用 getLibrary 方法时都会刷新。因此,如果您要确保媒体库中显示最新的图像,请在保存图像后等待一段时间再调用 getLibrary 方法。

Ionic 保存图片到图库并刷新媒体库

原文地址: https://www.cveoy.top/t/topic/oWXX 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录