Why does the Expo camera struggle to save photos to the gallery? It should be a simple task

  • I'm having an issue where I can successfully take a picture with a preview, but it's not saving to the gallery.

  • Even after adding MediaLibrary.createAssetAsync, the image preview doesn't show up and the picture still isn't saved locally.

I've been struggling with this problem for days now. Any tips or hints would be greatly appreciated.

//imports
import { Camera } from "expo-camera";
import * as MediaLibrary from 'expo-media-library';
import * as Permissions from 'expo-permissions';
  
// useState
const [hasPermission, setHasPermission] = useState(null);
const [rollPermision, setRollPermission] = useState(null);

// useEffect and ref to the camera
const cameraRef = useRef();

useEffect(() => {
    (async () => {
        const { status } = await Camera.requestPermissionsAsync();
        setHasPermission(status === "granted");
        // camera roll
        const { cam_roll } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
        setRollPermission(cam_roll === "granted");
        setRollPermission(true);
    })();
}, []);

// shutter button function to take picture
const takePicture = async () => {
    if (cameraRef.current) {
        const options = { quality: 0.5, base64: true, skipProcessing: true };
        const data = await cameraRef.current.takePictureAsync(options);
        //camera roll (saving picture)
        const asset = await MediaLibrary.createAssetAsync(data);

        const source = asset.uri;
        if (source) {
            await cameraRef.current.pausePreview();
            setIsPreview(true);
            console.log("picture source", source);
        }
    }
};

//if statement if it hit an error
if (hasPermission === null || rollPermision === null) {
    return <View />;
}
if (hasPermission === false || rollPermision === false) {
    return <Text style={styles.text}>No access to camera</Text>;
}

Answer №1

    const { uri } = await cameraRef.current.takePictureAsync(options);
      //saving the picture to camera roll
    const asset = await MediaLibrary.createAssetAsync(uri);

It is recommended to save data.uri instead of data itself. Upon console logging data, it will reveal that it stores an object with the image's uri stored in cache.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issue with dynamically passing select values to pop-up link in Firefox

My website has a select dropdown feature that triggers a confirmation pop up with the same selection when the user makes a choice. Upon clicking Submit, a new window opens with the corresponding link. Everything works smoothly in Safari, Chrome, and Opera ...

Retrieving a result from the reduce function in Angular

Is there a way to use the reduce function in order to return a list of objects? I am currently only able to return a single object with keys as project names and values as hours: { Name1: 9, Name2: 10, Name3: 30, } What changes can I make to my code to ac ...

When attempting to import and utilize global state in a component, the error message "Cannot iterate over null object"

I am in the process of setting up a global state to keep track of various properties that I need to pass down to multiple components. const initialState = { username: '', selectedCategory: null, categoriesList: [], createdTaskTopi ...

How to utilize Vue.js method to retrieve child prop?

In my Vue.js project, I have created two components. The main component uses a child component called NoteRenderer, which includes a prop named data_exchange. My goal is to update this prop from the main component when a button is clicked. I attempted to a ...

Can't get window.focus to work in JavaScript, but window.close is working fine

Goal: Notify the User before exiting the parent page if they have a Web Based Training Pop-up open. If they choose to stay on the page by clicking cancel, I want the focus to return to the pop-up. Currently, it remains minimized which is causing an issue. ...

What is the best way to effectively use combinedLatestWith?

https://stackblitz.com/edit/angular-ivy-s2ujmr?file=src/app/country-card/country-card.component.html I am currently working on implementing a search bar in Angular that filters the "countries$" Observable based on user input. My approach involves creatin ...

Determine the display width and height of an image by setting max-width and max-height to 100%

I am currently working on a slideshow that features images of different sizes. My goal is to have these images displayed in the center both vertically and horizontally within a canvas area. Within my CSS, I've specified the width and height of each i ...

Struggling with displaying and hiding div elements

Here is the code I'm currently working on: https://jsfiddle.net/Metalnoypi/d7ocf929/#&togetherjs=HD16R9BLLF I am relatively new to JavaScript, HTML, and CSS. I am facing an issue where the main menu page should disappear when the start button is ...

The error message "A form control with an invalid name attribute is not focusable" is displayed when attempting to use an input type file in Material

I've created a form using Material UI as a functional component, with the following structure: <form className={classes.container} onSubmit={show}> <Grid container item xs={12} alignItems="center"> <input accept=".xlsx,.xls" cl ...

Updating the load context variable in Django template after making changes via an AJAX call: a step-by-step guide

Here is the code snippet for displaying table items in my customer_items.html page: <table id="tblData" style="width: 100% !important;" class="display table table-bordered table-striped table-condensed"> <thead> <tr> ...

Modifying CSS classes using conditional statements and loops

var first_left = ['Photo', 'Info', 'Question 1', 'Question 2', 'Question 3', 'Question 4', 'Question 5']; var names = ['Abuela', 'Abuelo', 'Oma']; functio ...

jQuery - Show or hide content with a toggle action

Is there a way to toggle the text on a button once certain content is visible? Can the content be hidden if the button is clicked again? To better illustrate, check out this example: JSFiddle I am looking to switch the button text from 'View content ...

Vue alert: Issue encountered in watcher 'childItems' callback - 'TypeError: Unable to access property 'tag' as it is undefined'

I am currently in the process of developing the Store page for a web application. I am utilizing Axios to retrieve product data and display it in a Vue template. While the backend functionality is working correctly and the frontend is rendering successfull ...

Looking for guidance on JavaScript - Implementing a different font family for each div element

I need help with customizing the font family for each individual post on my website. Currently, I am able to assign a cursive font to all posts within a class, but I would like each post to have its own unique font. Since I am doing this on load, I am fa ...

Discovering the presence of a logo within an image using NodeJS

I'm currently investigating if it's possible to process an image on a nodeJS server to determine if it contains another image. For instance: Image 1: A picture of a laptop example: http://amasoncomputers.com/wp-content/uploads/2015/04/hp-630.jp ...

Issues persist with AngularJS integration using Modernizr

Incorporating AngularJS and Modernizr, I aim to identify media queries and trigger a function whenever the window or viewport is resized. My goal is to control element visibility based on whether the user is on a desktop or mobile device - certain elements ...

Discover the steps to transfer v-model data into the URL path within vue.js

I created a dashboard with a search button. When I input data into the search box, I want that data to be sent to my backend URL path so I can call my backend API. Can someone assist me in figuring out how to pass the v-model data to my URL path? Dashboar ...

Guide to changing the border color in a Material-UI TextField component styled with an outline design

To complete the task, utilize the Material UI outlined input field (TextField component from "@material-ui/core": "^4.12.2",) and apply a custom blue color style to it. Here is the outcome of my work: https://i.sstatic.net/lw1vC.png C ...

What is the best way to retrieve the value of the "Observer" object?

I am a user of Vue.js and I have the following data in this.suspendedReserveMemo: this.suspendedReserveMemo [__ob__: Observer]650: "memo3"651: "memo4"652: ""653: ""654: ""655: ""656: ""657: ""658: ""659: ""660:""661: ""662: ""length: 663__ob__: Observer {v ...

Measuring the size of a request in JavaScript using bytes

I'm trying to determine the byte size of a basic HTTP data transfer using Node.js. Let's say I'm sending a straightforward JSON string - how can I find out the size of the message body? Would saving the string to a .txt file provide an acc ...