Base64 Image Download in React Native: Simplified!

How do you download base64 images in React Native?

Quick Summary:Base64 images are a great way to store and transfer images online. They are also a popular way to embed images in HTML documents. So, if you want to save or download an image to your local device in React Native, you are surely wondering how to do it. If so, you need to read this article.

Introduction

As the world continually digitizes, everyone is adopting an approach to software development and applications. The preferred technology is still the React Native framework among developers. As it allows them to develop exceptional cross-platform applications with ease.

However, as your app evolves, your users’ expectations evolve simultaneously. Hence, it becomes compulsory to provide a better experience to users. Imagine the impact of enhancing your app with images that load swiftly and efficiently. It will enhance your user satisfaction and involvement.

Base64 images are a popular way to transfer images over the internet. Encoding shrinks their size and simplifies transmission, while enabling the decoding of their original form.

So, imagine providing the same to your users!

Wondering! How will it be possible to pull it off? And still, in confusion, why do you even need this? Why only React Native is the best for downloading Base64 images?

Read this write-up and find your answers…

You will read about why React Native Development Services will be the best for this.

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. Previously, we couldn’t transport large data quantities like files because they consisted of 28-bit bytes. However, our current network employs 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.
Sometimes people refer to Base64 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.

Base64 encoding can encode any string and involves 64 characters.

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

Why Download Base64 images?

The reasons for downloading and saving Base64 images can vary; read the following outlined possible reasons:

  • It can improve the performance of your app. When you load an image from a server, it takes time for the image to download. Hence, if you download an image to your local device first, it will be faster to load the next time the user sees it.
  • Downloading base64 images can save bandwidth. Additionally, if your app utilizes numerous images, downloading them to your local device can assist in reducing the volume of data requiring transfer over the internet.
  • By downloading the Base64 images, you can have more authority over the visuals. When you store the images on your local device, you can do things like cache them, resize them, or rotate them.
  • Base64-encoded images can increase the size of your JavaScript bundle, impacting the app’s initial loading time. It’s essential to balance reducing network requests and managing your bundle size.
  • Downloading images separately and caching them allows for better control over caching strategies. With Base64 images, you lose some of the built-in image caching and management that the device’s native image handling provides.
  • Using Base64-encoded images might limit your ability to update images without redeploying the app, which isn’t the case when fetching images from a remote server.
  • Embedding images directly in code or data can make your codebase less maintainable, as image changes would require code updates rather than just swapping out image files.
  • Base64-encoded images are more significant compared to their original binary representation. When dealing with bigger photos, this might result in greater memory utilization and performance issues.

Why Download Base64 images in React Native?

So you might be wondering why we are considering React Native for downloading Base64 images. Right? However, it’s not just React Native; it can be any other platform that supports JavaScript. Let us tell you why React Native is best for loading images.

1.JavaScript Environment

React Native uses JavaScript as its primary programming language. Base64 encoding and decoding are operations that can be easily performed using JavaScript functions. It makes it convenient to work with Base64-encoded data, including images.

2. Cross-Platform

You can create code using React Native that Works across iOS and Android platforms. You may utilize the same codebase to handle Base64 images on both platforms. It reduces the need for platform-specific code.

3. Component-Based

React Native’s component-based architecture allows you to create reusable UI components. You can easily create custom components for displaying Base64 images. It also manages them alongside other UI elements.

4. Native Modules

If needed, you can create native modules in React Native to handle more complex image processing tasks or leverage platform-specific features related to image manipulation and display.

5. Community and Libraries

React Native has a large and active community, so you’ll likely find libraries, tools, and resources to help you work with Base64 images more effectively. There may be solutions out there that are tailored to your particular needs.

To get more information about React Native, you must read the interesting FAQs About React Native.

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 particular 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.
  • The decimals will be converted to a string according to the table format using the base64 Index Table.

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.

Conclusion

Mastering the downloading of Base64 images in React Native empowers you to handle and store images locally efficiently. However, implementing this process can sometimes be intricate and time-consuming. That’s where BigScal comes in.

We at BigScal offer comprehensive solutions for React Native development. With our expertise, you can seamlessly integrate complex functionalities like downloading Base64 images. Our skilled developers will ensure that your app’s performance, scalability, and user experience remain top-notch. Save time and resources by partnering with BigScal to conquer even the most intricate aspects of React Native development. Elevate your app to new heights with BigSal’s support and expertise.

FAQ

To render base64 images in React Native, employ the ‘Image’ component. Set the ‘Source’ Prop to the base64-encoded image data preceded by “data:image/png;base64,” ‘(or appropriate format). The ‘Image’ component will handle rendering. Customize the component’s dimensions and styling to match your requirements.

To save base64 images in React, first convert the base64 data to a binary format using functions like the ‘File’ constructor or ‘Blob’ to create a file obh=ject from the binary data. Finally, you can utilize browser functionality like ‘URL. createObjectURL( )’ to generate a ‘FileSaver.js’ for more advanced options.

You can use local images in React without importing them by referencing their relative paths directly in the ‘src’ attribute of the ‘img’ tag. This approach will suit images placed within your project’s public directory. Remember that it might not offer the same optimization level as importing and won’t provide features like automatic resizing or transformations. Always consider your project’s requirements and performance implications when using this approach.

Base64 encoding is faster than the original image data regarding raw data processing. In a nutshell, Base64 encoding does not make images faster; it’s a method to represent binary data as text. Encoding adds processing time, and encoded data is more significant. It’s used for compatibility in text-based systems, not speed.

Base64 encoding converts binary data, like images, into a text format to ensure compatibility across systems that might handle data differently. It does this by dividing the data into chunks of 3 bytes, each composed of 8 bits. These 24 bits are then split into 4 chunks of 6 bits each. Each 6-bit chunk is converted into a character based on a predefined mapping table of 64 characters. It produces a text representation of the original binary data, which is safe to transmit over channels that might not support binary data directly. Due to this encoding overhead, base64-encoded images are more significant than their binary counterparts.