Camera & Media
Accessing the device camera and media files is essential for many apps. Let's learn how to capture photos, record videos, and pick files from the device.
Camera Access Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Camera & Media Flow โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ โ
โ Request Permission โ
โ โ โ
โ โผ โ
โ โโโโโโโโโโโโ โโโโโโโโโโโโ โ
โ โ Camera โ or โ Gallery โ โ
โ โโโโโโฌโโโโโโ โโโโโโฌโโโโโโ โ
โ โ โ โ
โ โผ โผ โ
โ Capture/Select Media โ
โ โ โ
โ โผ โ
โ Process & Upload โ
โ โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
React Native: Image Picker
import { launchCamera, launchImageLibrary } from 'react-native-image-picker';
// Take a photo
const takePhoto = async () => {
const result = await launchCamera({
mediaType: 'photo',
maxWidth: 1024,
maxHeight: 1024,
quality: 0.8,
});
if (!result.didCancel) {
const imageUri = result.assets[0].uri;
console.log('Photo taken:', imageUri);
// Upload to server
}
};
// Pick from gallery
const pickImage = async () => {
const result = await launchImageLibrary({
mediaType: 'photo',
maxWidth: 1024,
maxHeight: 1024,
});
if (!result.didCancel) {
const imageUri = result.assets[0].uri;
console.log('Image selected:', imageUri);
}
};
Flutter: image_picker
import 'package:image_picker/image_picker.dart';
import 'dart:io';
class CameraExample extends StatefulWidget {
@override
_CameraExampleState createState() => _CameraExampleState();
}
class _CameraExampleState extends State<CameraExample> {
File? _image;
final picker = ImagePicker();
Future<void> _takePhoto() async {
final pickedFile = await picker.pickImage(source: ImageSource.camera);
if (pickedFile != null) {
setState(() {
_image = File(pickedFile.path);
});
}
}
Future<void> _pickFromGallery() async {
final pickedFile = await picker.pickImage(source: ImageSource.gallery);
if (pickedFile != null) {
setState(() {
_image = File(pickedFile.path);
});
}
}
@override
Widget build(BuildContext context) {
return Column(
children: [
if (_image != null)
Image.file(_image!, height: 200),
ElevatedButton(
onPressed: _takePhoto,
child: Text('Take Photo'),
),
ElevatedButton(
onPressed: _pickFromGallery,
child: Text('Pick from Gallery'),
),
],
);
}
}
Permissions Required
- iOS: NSCameraUsageDescription, NSPhotoLibraryUsageDescription
- Android: CAMERA, READ_EXTERNAL_STORAGE, WRITE_EXTERNAL_STORAGE
- Always: Request permission before accessing camera or gallery