React Native调用摄像头画面及拍照和保存图片(含base64保存图片)到相册全流程
import React, { useState, useEffect } from 'react';
import { View, Text, TouchableOpacity, CameraRoll, Image } from 'react-native';
import { RNCamera } from 'react-native-camera';
export default function CameraComponent() {
const [cameraRef, setCameraRef] = useState(null);
const [photo, setPhoto] = useState(null);
const takePicture = async () => {
if (cameraRef) {
const data = await cameraRef.takePictureAsync();
setPhoto(data.uri);
}
};
const savePictureToRoll = async (photoUri) => {
const permissionResult = await CameraRoll.saveToCameraRoll(photoUri);
console.log('图片保存结果:', permissionResult);
};
useEffect(() => {
if (photo) {
savePictureToRoll(photo);
}
}, [photo]);
return (
<View>
<RNCamera
ref={(ref) => setCameraRef(ref)}
style={{ flex: 1 }}
type={RNCamera.Constants.Type.back}
flashMode={RNCamera.Constants.FlashMode.off}
/>
<TouchableOpacity onPress={takePicture}>
<Text>拍照</Text>
</TouchableOpacity>
{photo && <Image source={{ uri: photo }} style={{ width: 300, height: 300 }} />}
</View>
);
}
这段代码展示了如何在React Native应用中使用react-native-camera
库来实现调用摄像头、拍照以及将照片保存到相册的功能。它使用了useState
和useEffect
钩子来管理状态,并展示了如何使用RNCamera
组件来配置和引导摄像头。同时,它提供了一个takePicture
函数来捕获照片,并使用CameraRoll.saveToCameraRoll
方法将照片保存到相册中。
评论已关闭