保存一张拍摄很长时间的照片



我希望用户能够从我的应用程序中拍摄照片,并将照片保存到他们的图库中(这样我以后就可以在照片选择器中查看它们(。

我有以下来自react原生相机的代码,它基本上是最基本的演示代码。

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原生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应用程序时,通常需要几分钟才能最终加载图像。我已经在许多不同的设备上尝试过,包括模拟设备和物理设备。。。我做错什么了吗?谢谢

这是由于Android的媒体扫描程序没有立即意识到新文件的存在。

从这次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方法强制媒体扫描程序实现文件的存在。这是我需要清理的粗略代码,但它完成了任务。

最新更新