i'm working on app in expo to take and save image to device. I tried camera roll but it seems it's not supported in expo so is there any way to save image to device using expo
CodePudding user response:
Expo provides a package to save assets - https://docs.expo.dev/versions/latest/sdk/media-library/ (including images) to the device media library.
Storage access permission is required before attempting to save a file.
// Top-level module import
import * as MediaLibrary from "expo-media-library";
const saveImage = async (uri) => {
try {
// Request device storage access permission
const { status } = await MediaLibrary.requestPermissionsAsync();
if (status === "granted") {
// Save image to media library
await MediaLibrary.saveToLibraryAsync(uri);
console.log("Image successfully saved");
}
} catch (error) {
console.log(error);
}
};
CodePudding user response:
For taking a photo, Expo provides a plugin called ImagePicker.
import React, { useState, useEffect } from 'react';
import { Button, Image, View, Platform } from 'react-native';
import * as ImagePicker from 'expo-image-picker';
export default function ImagePickerExample() {
const [image, setImage] = useState(null);
const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
console.log(result);
if (!result.cancelled) {
setImage(result.uri);
}
};
return (
<View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
<Button title="Pick an image from camera roll" onPress={pickImage} />
{image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
</View>
);
}
You will also have to handle permissions.
If using a bare react native app, check out extra instructions here.