首页 > 解决方案 > 保存拍摄时间很长的照片

问题描述

我希望用户能够从我的应用程序中拍摄照片并将照片保存到他们的画廊(以便我以后可以在照片选择器中查看它们)。

我有以下来自 react-native-camera 的代码,它基本上是基本的演示代码。

takePicture() {
    const options = { quality: 0.5, fixOrientation: false, width: 1920 };
    if (this.camera) {
      this.camera
        .takePictureAsync(options)
        .then(data => {
             this.saveImage(data.uri);
        })
        .catch(err => {
          console.error("capture picture error", err);
        });
    } else {
      console.error("No camera found!");
    }
  }
}

为了移动附件,我使用的是 react-native-fs,如下(更基本的 demo-y 代码):

const dirHome = Platform.select({
  ios: `${RNFS.DocumentDirectoryPath}/Pictures`,
  android: `${RNFS.ExternalStorageDirectoryPath}/Pictures`
});

const dirPictures = `${dirHome}/MyAppName`;

saveImage = async filePath => {
    try {
      // set new image name and filepath
      const newImageName = `${moment().format("DDMMYY_HHmmSSS")}.jpg`;
      const newFilepath = `${dirPictures}/${newImageName}`;
      // move and save image to new filepath
      const imageMoved = await this.moveAttachment(filePath, newFilepath);
      console.log("image moved: ", imageMoved);
    } catch (error) {
      console.log(error);
    }
  };

  moveAttachment = async (filePath, newFilepath) => {
    return new Promise((resolve, reject) => {
      RNFS.mkdir(dirPictures)
        .then(() => {
          RNFS.moveFile(filePath, newFilepath)
            .then(() => {
              console.log("FILE MOVED", filePath, newFilepath);
              resolve(true);
            })
            .catch(error => {
              console.log("moveFile error", error);
              reject(error);
            });
        })
        .catch(err => {
          console.log("mkdir error", err);
          reject(err);
        });
    });
  };

拍照时,此代码会执行并打印图像已在几秒钟内移动。但是,当我查看设备上内置的 Gallery App 时,通常需要几分钟才能最终加载图像。我已经在许多不同的设备上尝试过这个,包括模拟的和物理的......我做错了什么吗?谢谢!

标签: androidreact-nativereact-native-camerareact-native-fs

解决方案


这是由于 Android 的 Media Scanner 没有立即意识到新文件的存在造成的。

从这个 Git 问题和随后的 PR:https ://github.com/itinance/react-native-fs/issues/79

我修改了我的代码如下:

  saveImage = async filePath => {
    try {
      // set new image name and filepath
      const newImageName = `${moment().format("DDMMYY_HHmmSSS")}.jpg`;
      const newFilepath = `${dirPicutures}/${newImageName}`;
      // move and save image to new filepath
      const imageMoved = await this.moveAttachment(filePath, newFilepath).then(
        imageMoved => {
          if (imageMoved) {
            return RNFS.scanFile(newFilepath);
          } else {
            return false;
          }
        }
      );
      console.log("image moved", imageMoved);
    } catch (error) {
      console.log(error);
    }
  };

使用 RNFS 的 scanFile 方法强制 Media Scanner 意识到文件存在。这是我需要清理的粗略代码,但它可以完成工作。


推荐阅读