我希望用户能够从我的应用中拍摄照片并将照片保存到他们的图库中(以便我以后可以在照片选择器中查看它们)。
我有以下来自 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 应用程序时,图像通常需要 几分钟 才能最终加载。我已经在许多不同的设备上尝试过这个,包括模拟设备和物理设备......我做错了什么吗?谢谢!
最佳答案
这是由于 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 方法强制媒体扫描器意识到文件存在。这是我需要清理的粗略代码,但它可以完成工作。
关于android - 保存一张花了很长时间的照片,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58829827/