保存花费很长时间的照片

时间:2019-11-13 03:19:07

标签: android react-native react-native-camera react-native-fs

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

我有来自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时,通常需要花费数分钟的时间才能最终加载图像。我已经在许多不同的设备(包括仿真设备和物理设备)上进行了尝试...我做错了什么吗?谢谢!

1 个答案:

答案 0 :(得分:0)

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

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

我修改了我的代码,如下所示:

awk '/START OF TEC MAP/,/END OF TEC MAP/' |
awk '/EPOCH OF CURRENT MAP/{print strftime("%d-%b-%Y %H:%M:%S",mktime($1" "$2" "$3" "$4" "$5" "$6))}' |
$1 == "70.0-180.0" {flag=1}
$1 == "57.5-180.0" {flag=0}
flag && $0 ~ "LAT/LON1/LON2/DLON/H"
awk '$ ~/LAT\/LON1\/LON2\/DLON\/H/ && FNR==2 {print $(NF-2)" "$(NF-1)" "$(NF)}' | awk '$ ~/LAT\/LON1\/LON2\/DLON\/H/ && FNR==3 {print $1}'

使用RNFS的scanFile方法强制媒体扫描器认识到该文件存在。这是我需要清理的粗略代码,但可以完成工作。