Onaracs
Onaracs

Reputation: 935

React Native Speed up converting image uri to base64

I'm working on a react native iOS app where I want to take certain images from a user's Camera Roll and save them in cloud storage (right now I'm using Firebase).

I'm currently getting the images off the Camera Roll and in order to save each image to the cloud I'm converting each image uri to base64 and then to a blob using the react-native-fetch-blob library. While this is working I am finding the conversion process to base64 for each image to be taking a very long time.

An example image from the Camera Roll: enter image description here

What would be the most efficient/quickest way to take the image uri for each image from the Camera Roll, convert it, and store it to cloud storage. Is there a better way I can be handling this? Would using Web Workers speed up the base64 conversion process?

My current image conversion process:

import RNFetchBlob from 'react-native-fetch-blob';
const Blob = RNFetchBlob.polyfill.Blob;
const fs = RNFetchBlob.fs
window.XMLHttpRequest = RNFetchBlob.polyfill.XMLHttpRequest
window.Blob = Blob

function saveImages(images) {
    let blobs = await Promise.all(images.map(async asset => {
        let response = await convertImageToBlob(asset.node.image.uri);
        return response;
    }));

    // I will then send the array of blobs to Firebase storage
}


function convertImageToBlob(uri, mime = 'image/jpg') {
    const uploadUri = uri.replace('file://', '');

    return new Promise(async (resolve, reject) => {
        let data = await readStream(uploadUri);
        let blob = await Blob.build(data, { type: `${mime};BASE64` });
        resolve(blob);
    })
}

function readStream(uri) {
    return new Promise(async (resolve, reject) => {
        let response = await fs.readFile(uri, 'base64');
        resolve(response);
    })
}

Upvotes: 4

Views: 6680

Answers (2)

Onaracs
Onaracs

Reputation: 935

I found the solution below to be extremely helpful in speeding up the process. The base64 conversion now takes place on the native side rather than through JS.

React Native: Creating a custom module to upload camera roll images.

It's also worth noting this will convert the image to thumbnail resolution.

To convert an image to full resolution follow guillaumepiot's solution here: https://github.com/scottdixon/react-native-upload-from-camera-roll/issues/1

Upvotes: 1

codeisforeva
codeisforeva

Reputation: 469

I would follow the example here form the react-native-fetch docs. It looks like you're trying to add an extra step when they take care of that for you.

https://github.com/wkh237/react-native-fetch-blob#upload-a-file-from-storage

Upvotes: 0

Related Questions