What is the process for transmitting images from React Native to native modules?

Challenge

I am facing an issue trying to send an array of locally saved images from the JavaScript side (stored in an assets folder) to both iOS and Android native sides. The native code processes the images and returns a new image successfully when using internet-based image URLs instead of local images. However, downloading each image individually is slow, especially when dealing with multiple images.

I believe the best solution would be to send the absolute paths of the images stored on the device.

What I've Attempted:

  • Sending image URLs (Works but not ideal as it involves downloading each image)

Potential Solutions:

  • One option could be to obtain an array of base64 strings for each image. However, this process seems time-consuming as the native side would need to convert each base64 string into data and then into images.

  • An alternative approach could involve sending the absolute URI path for each asset. Unfortunately, finding a method to retrieve this path has proved challenging, as only relative paths have been discovered so far (e.g., './assets/myImage.png')

As per the React Native documentation (https://facebook.github.io/react-native/docs/native-modules-ios.html), the native side supports JSON standard formats, including strings, numbers, booleans, arrays, objects of any type, and React callbacks/promises.

Answer №1

When retrieving a local image file on the JavaScript side, you are not actually receiving the image data itself. Instead, React Native creates a mapping of IDs to images; if you attempt to log it, you will see that it is simply just a number.

Although numbers can be sent over the bridge, this alone is insufficient. In order to access the image on the native side, you must first resolve the required image to an object that can later be converted in native code. On the JavaScript side, it would appear something like this:

const myImage = require('./my-image.png');
const resolveAssetSource = require('react-native/Libraries/Image/resolveAssetSource');
const resolvedImage = resolveAssetSource(myImage);

You can then pass the resolvedImage to your native API, which will contain a dictionary object (a map) with information about the image (size, uri, etc.). In native code, you can convert the image like so:

UIImage *image = [RCTConvert UIImage:imageObj];

On Android, the process is similar, but there are no direct conversion methods available. Therefore, you will need to extract the uri from the image map object and load it from there.

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

What is the method for retrieving the fixed information?

I am currently working on a project that involves creating a course-rating API. We have been given a completed angular application to work with, and our task is to set up the routes without making any changes to the Angular app. One of the initial tasks a ...

Mysterious data organization - transform into an object

As I interact with an API, there is a value that I cannot quite pinpoint. My goal is to transform this string into a JavaScript object, but the process seems complex and confusing. Does anyone have insight on what this data represents and how it can be co ...

Issues with CSS properties not functioning correctly within the class.col function

When attempting to apply specific CSS properties to a particular area (e.g., "Dashboard") by assigning the class name "main" to the div.col function in the HTML, I encountered an issue where the CSS property applied affected the entire page. The following ...

Utilize the capabilities of the Dropbox Core API in Javascript to effortlessly transfer and store files on

I am currently developing a chrome-extension that has the ability to upload files to the user's Dropbox folder. I have implemented AJAX requests in my code to handle file uploads, and it is working fine for text-based file extensions such as .txt, .js ...

Patience is key when waiting for both subscriptions to be completed before proceeding with an

I am facing a challenge with two subscriptions as shown below: this.birthdays = await this.birthdaySP.getBirthdays(); this.birthdays.subscribe(groups => { const allBirthdayT = []; groups.map(c => { allBirthdayT.push({ key: c.pa ...

Determining the typing of a function based on a specific type condition

I have created a unique type structure as shown below: type Criteria = 'Criterion A' | 'Criterion B'; type NoCriteria = 'NO CRITERIA'; type Props = { label?: string; required?: boolean; disabled?: boolean; } & ( | ...

The Node.js error message "Module not found"

Currently, I am working through the node.js tutorial on Lynda.com and encountering an issue with the "Error: Cannot find module". Despite having the flight module listed in the package.json file, the error persists. Up until this point, everything has bee ...

I created a custom discord.js-commando command to announce all the channels that my bot is currently active in, however, encountered an unexpected error

const Commando = require('discord.js-commando'); module.exports = class AnnounceCommand extends Commando.Command { constructor(client) { super(client, { name: 'announce', aliases: ['an'], ...

Utilizing Dropzone for file uploads in Node.js, Express, and Angular

I'm running into a bit of trouble trying to get the file recognized on the server side with node.js. Especially when trying to access request data, such as req.files or req.body If anyone has any advice, here are some code snippets: HTML: <form ...

Trigger the function upon displaying the modal

Within my Bootstrap project, I have set up a click event to trigger a modal as follows: $('#make_selects_modal').appendTo("body").modal('show'); My requirement is to run a function called pickClient when this modal is displayed. I att ...

Instead of modifying the selected class, jQuery generates inline styles

Utilizing the following code to dynamically create a class: $("head").append('<style type="text/css"></style>'); var newStyleElement = $("head").children(':last'); newStyleElement.html('.move{transform: translateX(1 ...

Troubleshooting a Vue.js issue: How to fix a watch function that stops working after modifying

I have encountered a problem with my code. It seems to be working fine initially after the beforeMount lifecycle hook, but when I try to modify the newDate variable within my methods, it doesn't seem to track the changes. data() { return { ...

React state change is causing a functional component to not re-render

When attempting to map out a nested array from the data retrieved by an http request in a functional component, you may encounter a frustrating error: "TypeError: Cannot read property 'map' of undefined". Even though the state is updated correctl ...

Connecting a Kendo Dropdown menu to external data sources for seamless integration

I need help with binding data to a dropdown list for my local service. Whenever I try to download the data, I keep getting an error message: Uncaught SyntaxError: Unexpected token: Does anyone have any ideas on how to resolve this issue? This is my JS ...

Utilizing the Power of Mui Datatable to Enhance User Experience with Repeatable Edit and Delete

Hey Everyone, I'm currently trying to implement edit and delete buttons in ReactJS using Mui Datatable. However, I am facing a recurring issue due to the Map function since I am relatively new to ReactJS. Below is my image and code snippet: Here is a ...

What might be the reason my $q.defer().resolve is not functioning properly?

I have noticed an interesting behavior in my code. When I define a promise in the service and return it back (promise1 in this case), it does not resolve at all. However, when I define the promise in the controller (promise2), it works perfectly fine. Why ...

Terminate multiple axios requests using a common CancelToken

Within a single view, I have multiple react modules making API calls using axios. If the user navigates to another view, all ongoing API calls should be canceled. However, once they return to this view, these calls need to be initiated again (which are tri ...

Incorporating CSS styles for attributes in React Material UI

In this scenario, I have integrated the <AppBar/> component with custom properties like iconElementRight. However, upon inspecting in the browser, I noticed that the iconElementRight appears within a separate div. To address this issue, I am lookin ...

How to Access a Method from Controller 2 in AngularJS Controller One

angular.module('starter.controllers', []) .controller('controller1',function($scope) { $scope.function1= function () { // Code for controller1 function } }) .controller('controller2',fun ...

What is causing the presence of NaN?

Initially: https://i.stack.imgur.com/2n1Zk.png After Interaction: https://i.stack.imgur.com/Of0pO.png $(document).ready(function () { var output = document.getElementById("whole"); if (!navigator.geolocation) { ...