How to Download Base64 Images to your local device in React Native

How do you download base64 images in React Native?

React Native allows image conversion in your app using the Image component. However, you cannot use this component to convert base64 images. In fact, you cannot use the base64 format for images in React Native without a specific API. However, you can download base64 images using a JavaScript API provided by React Native. This article will show you how to do just that.

What is base64?

Base64 is a binary-to-text encoding method that shows binary data as an ASCII string. Base64 is a protocol for delivering binary information across multiple channels. It transforms any type of information into a long string of plain text. Due to the fact that files consist of 28-bit bytes, we were not able to transport large amounts of data via our network. Our current network uses 27-bit bytes. Base64 encoding came in handy at this point. But, what does base64 mean exactly?

Let’s glance at the definition of base64.

base64 is equal to base+64.

Base64 is sometimes known as a radix-64 representation.

To ensure that the written data is human-readable, base64 uses only 6-bits (26 = 64 characters).

Why only 64? Why not base65 or base78? Let’s put it to the test.

Any string can be encoded using base64 encoding, which has 64 characters.

Base64 has numeric values, 26 uppercase alphabets,26 lowercase alphabets ,two special characters i.e., +,/. Depends upon your OS.

Hire React Native Developers

How to convert into base64 encoding?

Let’s see how string can be converted into base64.
To convert string to base64 algorithm works as follows:

The length of characters in a String is counted.
Pad with a special character, including such =, if it is not a multiple of 3 then it will pad with single = character and In ASCII format, encode the string.
It will now convert each ASCII character to an 8-bit binary representation.
It will divide binary data into 6-bit chunks following converting to binary format.
The 6-bit binary data chunks will now be converted to decimal numbers.
By using the base64 index table, we will convert decimals into strings.

Now, we will see how to download the base64 converted image to our device.
First, to download it to our devices we will need to give permission to write and read external storage.
To give permission to our iOS and Android devices, we use a package called react-native-permission.
link:https://www.npmjs.com/package/react-native-permissions

After setting up the permission library we will install
yarn add rn-fetch-blob
cd ios && pod install

import { StackActions } from '@react-navigation/native'
import React, { useEffect, useState } from 'react'
import { ActivityIndicator, Image, SafeAreaView, StyleSheet, Text, TextInput, TouchableOpacity, View, Platform, Alert, Keyboard, ScrollView, Linking } from 'react-native'
import RNFetchBlob from 'rn-fetch-blob'
import { PERMISSIONS, checkMultiple, requestMultiple } from 'react-native-permissions';

const ImageShow= (pro​​ps) => {

const image=`<base64_url>` 

const saveImage = async () => {
await permission()
let date = new Date();
const { config, fs } = RNFetchBlob
const dirPath = Platform.OS == 'ios' ? `${fs.dirs.LibraryDirectoryPath}/<folder-name>` : `${fs.dirs.PictureDir}`
const filePath = dirPath + '/' + Math.floor(date.getTime() + date.getSeconds() / 2) + '.png'
fs.writeFile(filePath,qr, 'base64').then(res => {
Platform.OS === 'ios' ?
RNFetchBlob.ios.previewDocument(filePath) :
RNFetchBlob.fs.scanFile([
{ path: filePath, mime: 'image/png' },
])
Platform.OS === 'android' && Alert.alert(Constant.APPNAME, "image Successfully downloaded!!")
}).catch(err => console.log("err", err))
}

const permission = async () => {
const checkPermission = await checkMultiple(Platform.OS === 'android' ? [PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE, PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE] : [PERMISSIONS.IOS.PHOTO_LIBRARY, PERMISSIONS.IOS.PHOTO_LIBRARY_ADD_ONLY])
if (checkPermission['ios.permission.PHOTO_LIBRARY'] === 'denied' || checkPermission['ios.permission.PHOTO_LIBRARY_ADD_ONLY'] === 'denied' || checkPermission['android.permission.WRITE_EXTERNAL_STORAGE'] == 'denied' || checkPermission['android.permission.READ_EXTERNAL_STORAGE'] == 'denied') {
const requestPermission = await requestMultiple(Platform.OS === 'android' ? [PERMISSIONS.ANDROID.WRITE_EXTERNAL_STORAGE, PERMISSIONS.ANDROID.READ_EXTERNAL_STORAGE] : [PERMISSIONS.IOS.PHOTO_LIBRARY, PERMISSIONS.IOS.PHOTO_LIBRARY_ADD_ONLY])
}
}

return (
<SafeAreaView style={styles.container}> 
{qr!= '' && <View style={{ marginTop: 30 }}>
<View style={{}}>
<View style={{ flexDirection: 'row' }}>
<TouchableOpacity onPress={() => saveImage('download')}>
<Text style={{ color: Colors.BLACK }}>Download</Text>
</TouchableOpacity>
</View>
</View>
<Image style={{ width: Constant.SCREEN_WIDTH - 40, height: Constant.SCREEN_HEIGHT / 2, resizeMode: 'contain', marginTop: 0 }} source={{ uri:${image}` }} />
</View>}
</ScrollView>
</SafeAreaView>
)
}

export default ImageShow

const styles = StyleSheet.create({
container: {
flex: 1,
margin: 20
},
})

Initially, I thought that React Native does not support images in base64 format with the <Image> component. However, that is not true. It is possible to load base64 encoded images by decoding them to base64 format on the server side and sending a data URI. After the image loads the user can save the image to their local device. There is a way to download base64 images in React Native, but it is not obvious.

0 replies

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply