android - 将捕获的图像从相机保存到自定义文件夹 react native

标签 android react-native react-native-camera

所以我正在使用 react-native 创建一个简单的相机应用程序。对于相机组件,我使用的是 react-native-camera 包。到目前为止,我可以使用 react-native CameraRoll Api CameraRoll.saveToCameraRoll 拍摄照片并将其保存到 DCIM 文件夹中,但我想将其保存在另一个文件夹中,例如 DCIM/CameraAppPictures 文件夹中。为此,我使用了 RNFetchBlob 包。我尝试了几种方法从 this.camera.takePictureAsync 返回的 uri 创建一个新文件,但它会抛出文件不存在的错误。但是,如果我将该 uri 传递给 CameraRoll.saveToCameraRoll,它会将其保存在 DCIM 文件夹中。

我当前的代码:

    const options = { quality: 0.5 };

    const data = await this.camera.takePictureAsync(options)
    const { uri, height, width } = data;
    this.setState({ uri, height, width });

    CameraRoll.saveToCameraRoll(data.uri, 'photo') // it saves it into DCIM
    .then( uri => {
        // tried this too
        //RNFetchBlob.fs.createFile(`${RNFetchBlob.fs.dirs.DCIMDir}/newfile.png`, uri, 'uri'); // throws error that file does not exist
        RNFetchBlob.fs.cp(`${RNFetchBlob.fs.dirs.DCIMDir}`, `${RNFetchBlob.fs.dirs.DCIMDir}/CameraApp/p.png`);  
        console.warn('uri:', uri)
    })
    .catch( err => console.warn('err:', err));
    console.warn(data);

我尝试了一些奇怪的方法来将文件保存在我想要的地方但徒劳无功。我希望我已经明确了我的 Intent ,但如果您需要更多信息,请告诉我。欢迎提出任何建议。

最佳答案

**我可以创建目录,但我无法将图像移动到该目录,但是您可以检查它是否对您有帮助。!! **

import React from 'react';
//import react in our code. 
import { StyleSheet, Text, View, 
Alert, ActivityIndicator, PermissionsAndroid } from 'react-native';
//import all the basic components we are going to use.
import { CameraKitCameraScreen } from 'react-native-camera-kit';
//import CameraKitCameraScreen we are going to use.
import RNFetchBlob from 'react-native-fetch-blob'

export default class App extends React.Component {
state = {isPermitted:false}
constructor(props) {
super(props);
var that=this;
async function requestCameraPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.CAMERA,{
'title': 'CameraExample App Camera Permission',
'message': 'CameraExample App needs access to your camera '
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
//If CAMERA Permission is granted
//Calling the WRITE_EXTERNAL_STORAGE permission function
requestExternalWritePermission();
} else {
alert("CAMERA permission denied");
}
} catch (err) {
alert("Camera permission err",err);
console.warn(err)
}
}
async function requestExternalWritePermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.WRITE_EXTERNAL_STORAGE,{
'title': 'CameraExample App External Storage Write Permission',
'message': 'CameraExample App needs access to Storage data in your SD Card '
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
//If WRITE_EXTERNAL_STORAGE Permission is granted
//Calling the READ_EXTERNAL_STORAGE permission function
requestExternalReadPermission();
} else {
alert("WRITE_EXTERNAL_STORAGE permission denied");
}
} catch (err) {
alert("Write permission err",err);
console.warn(err)
}
}
async function requestExternalReadPermission() {
try {
const granted = await PermissionsAndroid.request(
PermissionsAndroid.PERMISSIONS.READ_EXTERNAL_STORAGE,{
'title': 'CameraExample App Read Storage Write Permission',
'message': 'CameraExample App needs access to your SD Card '
}
)
if (granted === PermissionsAndroid.RESULTS.GRANTED) {
//If READ_EXTERNAL_STORAGE Permission is granted
//changing the state to re-render and open the camera 
//in place of activity indicator
that.setState({isPermitted:true})
} else {
alert("READ_EXTERNAL_STORAGE permission denied");
}
} catch (err) {
alert("Read permission err",err);
console.warn(err)
}
}
//Calling the camera permission function
requestCameraPermission();
}
onBottomButtonPressed(event) {

if (event.type) {
//const captureImages = JSON.stringify(event.captureImages);

if (event.type == "capture") {

const pictureFolder = RNFetchBlob.fs.dirs.SDCardDir+'/Optimize/';
const captureImageLength = event.captureImages.length;
RNFetchBlob.fs.exists(pictureFolder).then((exists)=>{
if(exists){
RNFetchBlob.fs.isDir(pictureFolder).then((isDir)=>{
if(isDir){

RNFetchBlob.fs.mv(event.captureImages[0].uri, RNFetchBlob.fs.dirs.SDCardDir+'/Optimize/').then(() => {
alert('Image Moved');
}).catch((e)=>{ alert("FAILED:= "+e.message) });
}else{
alert('Some Error Happened');
}
}).catch((e)=>{ alert("Checking Directory Error : "+e.message); });
}else{
RNFetchBlob.fs.mkdir(pictureFolder).then(()=>{
alert('DIRECTORY CREATED');
}).catch((e)=>{ alert("Directory Creating Error : "+e.message); });
}
});
}
}
}
render() {
if(this.state.isPermitted){
return (
<CameraKitCameraScreen
// Buttons to perform action done and cancel
actions={{ rightButtonText: 'Done', leftButtonText: 'Cancel' }}
onBottomButtonPressed={event => this.onBottomButtonPressed(event)}
flashImages={{
// Flash button images
on: require('./assets/flashon.png'),
off: require('./assets/flashoff.png'),
auto: require('./assets/flashauto.png'),
}}
cameraFlipImage={require('./assets/flip.png')}
captureButtonImage={require('./assets/capture.png')}
/>
);
}else{
return ( 
<ActivityIndicator />
)
}
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});

关于android - 将捕获的图像从相机保存到自定义文件夹 react native ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52653938/

相关文章:

android - 使用 appcelerator 自动缩放字体大小是否适用于 android?

安卓 : Images and video path in same cursor without cursorLoader

javascript - 如何将 Prop 传递给 Redux Form 中的 onSubmitSuccess 回调?

javascript - React - 使用状态之外的函数设置组件状态,这是错误的吗?

React-native-camera 限制条码扫描区域

react-native - React Native (Android) 中的屏幕截图

java - 如何在android studio中实现观察者模式?

安卓模拟器 : How can I get a list of services that are running

reactjs - 上传到 Firebase 存储执行,但图像返回为黑色方 block 。尝试了一切

reactjs - 如何使用react-native-camera捕获的图像