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

Tips for enabling browser back and forward functionality in a one-page website design

Building on the previous discussion about optimizing a horizontal sliding layout (Most efficient way to do a horizontal sliding layout), I'm curious if it's feasible to enable the back and forward buttons in the browser when implementing a single ...

What is causing the malfunction in this code? (Regarding the key and value variable objects)

var elements = []; var attribute1 = $(index).attr('class'); //or any string var attribute2 = $(index).html(); //or any string elements.push({ attribute1: attribute2 }); When I run this code, the output I receive is: this Why am I unable to set ...

Restful Spinner

app.config(function(RestangularProvider) { RestangularProvider.addRequestInterceptor(function(element) { console.log("Request initiated"); return element; }); RestangularProvider.addResponseInterceptor(function(data) { ...

Navigate from the RootViewController to the NavigationController

Within my app, the initial view is a StartViewController which is embedded in a UINavigationController. This StartViewController is essentially a UITableViewController. The user can navigate to the SettingsViewController, also a UITableViewController withi ...

What is the reason that setTimeout does not delay calling a function?

I am looking to develop a straightforward game where a div is duplicated recursively after a short interval. Each new div should have a unique ID (ID+i). The concept is to continuously generate divs that the user must click on to remove before reaching a ...

The module in Node.js is unable to be loaded

Dealing with a common problem here. Despite trying to reinstall npm, deleting node_modules files and package-lock.json, the issue persists. The console output is as follows: node:internal/modules/cjs/loader:1080 throw err; ^ Error: Cannot find module &apo ...

How can the main activity be updated to detect changes in preferences?

I am using SharedPreferences in my app to store user preferences. SharedPreferences myPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext()); One of the preferences I am retrieving is for a checkbox with the key "checkbox". ...

Obtaining a byte array using the file input method

var profileImage = fileInputInByteArray; $.ajax({ url: 'abc.com/', type: 'POST', dataType: 'json', data: { // Other data ProfileImage: profileimage // Other data }, success: { } }) // Code in Web ...

Issue with PHP $_GET function not functioning properly in conjunction with JQuery Mobile

I am currently developing an application using a combination of JQuery Mobile and PHP. The issue at hand is as follows: I am encountering difficulties when attempting to transfer values between different pages in my JQuery mobile app (for example, from #p ...

NPM is searching for the package.json file within the user's directory

After completing my test suite, I encountered warnings when adding the test file to the npm scripts in the local package.json. The issue was that the package.json could not be located in the user directory. npm ERR! path C:\Users\chris\pack ...

Is there a way to avoid NetworkOnMainThreadException when utilizing Retrofit in a separate thread on Android?

Attempting to utilize the Retrofit library to download a 2MB apk file from a URL in a separate thread. Referencing code from this tutorial: : public class MainActivity extends AppCompatActivity { String fileUrl = "....."; @Override protecte ...

Eliminate the prior click action from the document object model

I am working with a set of elements that each have unique IDs and contain a span tag with the same image. For example: Under each element, there is a save icon. When a user clicks on it, the icon changes to a non-save icon. The issue arises when I click ...

Explanation of JavaScript code snippet

fnTest = /abc/.test(function () { abc; }) ? /\bchild\b/ : /.*/; I am struggling to comprehend the functionality of this particular javascript snippet. Would someone be able to elaborate on the logic behind this code fragment? ...

Best practices for working with HTML elements using JavaScript

What is the best approach for manipulating HTML controls? One way is to create HTML elements dynamically: var select = document.getElementById("MyList"); var options = ["1", "2", "3", "4", "5"]; for (var i = 0; i < options.length; i++) { var opt = ...

A guide on extracting specific text from a div class

<div class="col_5"> <br> <i class="phone"> :: Before </i> 0212 / 897645 <br> <i class="print"> ...

Tips for restricting additional input when maximum length is reached in an Angular app

In my Angular 6 application, I am working on implementing a directive that prevents users from typing additional characters in an input field. However, I want to allow certain non-data input keys such as tab, delete, and backspace. Currently, I have an if ...

Is there a way to display a UIDatePicker within a Popover on an iPad by utilizing Storyboard?

I successfully displayed the datepicker inside a popover programmatically, following the method shown in UIDatePicker in UIPopover. However, I attempted to achieve the same result using Interface Builder. I created a View Controller named DatePickerViewCo ...

How can I efficiently locate identical sequences of cells in two or more arrays?

Unique Example 1 We can explore an interesting scenario by considering two arrays: ('m','o','o','n','s','t','a','r','d') ('s','t','a', ...

What is the best way to sequentially invoke an asynchronous function within an Observable method?

Presently, I have the following method: public classMethod( payload: Payload, ): Observable<Result> { const { targetProp } = payload; let target; return this.secondClass.secondClassMethod({ targetProp }).pipe( delayWhen(() ...

Sending a multi-dimensional array to the server using PHP via POST

Similar Question: multi-dimensional array post from form I am looking to transfer data from the client to the PHP server using jQuery's $.post() method. Once the data reaches the server, I want the $_POST['myList'] variable to be in one ...