Deep Dive into Implementing react-native-image-picker (2024)

Providing users with the ability to upload pictures on their profiles is standard in modern applications. It is very important to give users the best experience so they can keep coming back to your app.

If you’re building your mobile app with React-Native, this is very easy to accomplish thanks to react-native-image-picker.

The first question you have to ask yourself is “What image types should my app support?”. There are a plethora of image types out there, and it can get overwhelming and confusing especially if you want your app to cater to all kinds of people. React Native actually makes this super easy for us.

“The currently supported formats are png, jpg, jpeg, bmp, gif, webp, psd (iOS only). In addition, iOS supports several RAW image formats.”

So you can narrow down your choices. Not mentioned in this list is the Base64. Base64 is a group of binary-to-text encoding schemes that represent binary data.

What is React Native Image Picker?

React-Native-Image-Picker is a React Native module that allows you to use native UI to select media from the device library or directly from the camera. It is currently used by almost 60 000 developers, as it is quite robust in what it offers.

Installing and setting up React-Native-Image-Picker

Start by installing the package to your project:

Android:

yarn add react-native-image-picker

iOS:

npx pod-install ios

On the react-native-image-picker repository, there is advise on some post-install steps. These include:
If you are allowing user to select image/video from photos, add NSPhotoLibraryUsageDescription.

iOS

If you are allowing user to capture image add NSCameraUsageDescription key also.

If you are allowing user to capture video add NSCameraUsageDescription add NSMicrophoneUsageDescription key also.

Android

Permissions are not required unless you have the saveToPhotos property set to true.

Permissions for iOS go in the Info.plist file in the test folder as follows:

<key>NSPhotoLibraryUsageDescription</key>
<string>$(PRODUCT_NAME) would like access to your photo gallery</string>
<key>NSCameraUsageDescription</key>
<string>$(PRODUCT_NAME) would like to use your camera</string>

Permissions for Android go into the AndroidManifest.xml file :

The React-Native-Image-Picker module does not need permissions to work for your users, but if you do set up the option to save images captured on the app to gallery, you will need one permission:

<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>

Here you are asking your user for permission to access their gallery and save the images captured from the application to their gallery.

Implementing React-Native-image-Picker

Create a component Profile.js. react-native-image-picker has two methods we can use; launchCamera() which will launch the camera to take a picture and launchImageLibrary() which will launch the gallery to pick a picture or video. We will import these into our file.

The launchLibrary method launches the user’s gallery and takes two parameters; configurations for the image and a response.

Image/video captured via camera will be stored in temporary folder so will be deleted any time, so don’t expect it to persist. Use saveToPhotos: true (default is false) to save the file in the public photos. saveToPhotos requires WRITE_EXTERNAL_STORAGE permission on Android 28 and below (You have to obtain the permission, the library does not).

The launchCamera method launches the user’s camera and and also takes two parameters; configurations for the image and a response.

The pickerResponse state variable is to save the response from the image picker. The imageFromDB state variable is to save the image from the database so we can access it later.

We use the Image component as follows:

<Card style=//card styles, specifically if you want the image to have elevation>
<Image
source={{
uri: `data:image/*;base64,${imageFromDB}`,,
width: ..,
height: ...,
}}
style=//extra image styles
/>
</Card>

This line of code

uri: `data:image/*;base64,${imageFromDB}`,

means that we use the uri property to render the image from the database and image/* is a catchall that will make sure that the component renders whichever image type.

We can also add a pressable icon to activate a modal where the user can choose to access their gallery or camera to upload an image.

 <Pressable
style={({ pressed }) => [
{
...styles.cameraIconView,
opacity: pressed ? 0.5 : 1,
},
]}
onPress={() => setVisible(true)}
>
<IconComponent
source={icons.camera}
tintColor={themeColor.primaryWhite}
/>
</Pressable>

We want to put the modal in our Profile component and pass it all the necessary properties.

<ImagePickerModal
isVisible={visible}
onClose={() => setVisible(false)}
onImageLibraryPress={onImageGalleryPress}
onCameraPress={onCameraPress}
/>

Finally, we will need to create an ImagePickerModal component.

For those of you wondering why we are using a base64 image instead of sending the image as is to the database, base64 encoding reduces the size of data by up to 33% and many programming languages have built in support for base64 encoding.

To render our image, we will be looking at 3 cases:

  1. The user is not logged in
  2. The user is logged in but does not have a profile image
  3. The user is logged in and does have a profile image
  4. The user is logged in and just changed their profile image
userLoggedIn ? {
uri ? (
<Card style={styles.userDBImageView}>
<Image
source={{
uri: uri,
width: styles.userDBImage.width,
height: styles.userDBImage.height,
}}
style={styles.userDBImage}
/>
</Card>
) : imageFromDB ? (
<Card style={styles.userDBImageView}>
<Image
source={{
uri: `data:image/*;base64,${imageFromDB}`,
width: styles.userDBImage.width,
height: styles.userDBImage.height,
}}
style={styles.userDBImage}
// tintColor={colors.primaryWhite}
/>
</Card>
) : (
<Card
style={{
...styles.userImageView,
marginTop: '8%',
width: '25%',
}}
>
<Image
source={icons.profileImage}
style={styles.userImage}
tintColor={colors.primaryWhite}
/>
</Card>
)
) : (
<Card style={styles.userImageView}>
<Image
source={icons.profileImage}
style={styles.userImage}
tintColor={colors.primaryWhite}
/>
</Card>
)
}

User is not logged in

The last component will be the one to be called when the user is not logged in, so the source for that image should be the default/fallback image.

The user is logged in but does not have a profile image

When the user is logged in but does not have a profile image, we will show the same image as when the user is not logged in, which is the second last component in the code.

The user is logged in and does have a profile image

The second component is rendered when a check has been executed to see if the user has logged in and if the user has an image from the database

The user is logged in and just changed their profile image

This code snippet first looks at if the user has selected/captured a new image using the uri variable. If there is a value for uri, it will immediately get displayed since it has precedence over the other variables in the ternary operator.

react-native-image-picker makes implementing image uploading capabilities very easy. It is so robust in its offering that you can easily build yourself an application where users can upload images and videos. It also helps make user experience pleseant but the best part about it is that it makes the developer experience even more enjoyable.

Deep Dive into Implementing react-native-image-picker (2024)
Top Articles
VeChain Vs. Ethereum 2.0 - Everything You Need to Know - Securities.io
Navigating Fresh Grads Career Paths: Internship vs. Graduate Trainee Program
Victor Spizzirri Linkedin
Safety Jackpot Login
Limp Home Mode Maximum Derate
Terraria Enchanting
Nm Remote Access
Farmers Branch Isd Calendar
Housing Intranet Unt
Space Engineers Projector Orientation
Dutchess Cleaners Boardman Ohio
Rainfall Map Oklahoma
"Une héroïne" : les funérailles de Rebecca Cheptegei, athlète olympique immolée par son compagnon | TF1 INFO
Classic | Cyclone RakeAmerica's #1 Lawn and Leaf Vacuum
Copart Atlanta South Ga
Cta Bus Tracker 77
Accident On 215
Melissababy
Is Windbound Multiplayer
Ford F-350 Models Trim Levels and Packages
Azur Lane High Efficiency Combat Logistics Plan
Reborn Rich Kissasian
Which Sentence is Punctuated Correctly?
Chime Ssi Payment 2023
Reicks View Farms Grain Bids
Kentuky Fried Chicken Near Me
Walmart Pharmacy Near Me Open
55Th And Kedzie Elite Staffing
Catchvideo Chrome Extension
031515 828
FSA Award Package
Laveen Modern Dentistry And Orthodontics Laveen Village Az
King Soopers Cashiers Check
Learn4Good Job Posting
Myhrconnect Kp
Cross-Border Share Swaps Made Easier Through Amendments to India’s Foreign Exchange Regulations - Transatlantic Law International
Bimar Produkte Test & Vergleich 09/2024 » GUT bis SEHR GUT
Dallas City Council Agenda
Bimmerpost version for Porsche forum?
20+ Best Things To Do In Oceanside California
Tirage Rapid Georgia
Saybyebugs At Walmart
Metro Pcs Forest City Iowa
Funkin' on the Heights
Petfinder Quiz
Nearest Wintrust Bank
New Starfield Deep-Dive Reveals How Shattered Space DLC Will Finally Fix The Game's Biggest Combat Flaw
Walmart Front Door Wreaths
Spongebob Meme Pic
Anthony Weary Obituary Erie Pa
7 National Titles Forum
Latest Posts
Article information

Author: Carlyn Walter

Last Updated:

Views: 5640

Rating: 5 / 5 (50 voted)

Reviews: 89% of readers found this page helpful

Author information

Name: Carlyn Walter

Birthday: 1996-01-03

Address: Suite 452 40815 Denyse Extensions, Sengermouth, OR 42374

Phone: +8501809515404

Job: Manufacturing Technician

Hobby: Table tennis, Archery, Vacation, Metal detecting, Yo-yoing, Crocheting, Creative writing

Introduction: My name is Carlyn Walter, I am a lively, glamorous, healthy, clean, powerful, calm, combative person who loves writing and wants to share my knowledge and understanding with you.