React Native image crop picker simplifies the process of selecting and cropping images in React Native applications. It simplifies the process of working with images by offering us a convenient and efficient way to integrate image-related functionalities in React Native projects.
Install react-native-image-crop-picker
Open the terminal and navigate to your project directory. Then, run the following command to install the react-native-image-crop-picker
:
npm install react-native-image-crop-picker // using npm
// OR
yarn add react-native-image-crop-picker // using yarn
For iOS, you also need to install pods in the iOS directory and then return to the root project directory. You can do this using the following commands:
cd ios
pod install
cd ..
Configure permissions
To access the device’s photo library and camera, we need to configure the required permissions. Add permissions for each platform:
Android
Open the AndroidManifest.xml
file from the android/app/src/main
directory of your project. Add the following lines inside the <manifest>
tag:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
<uses-permission android:name="android.permission.CAMERA" />
iOS
Open the Info.plist
file from the ios directory and add the following lines:
<key>NSPhotoLibraryUsageDescription</key>
<string>Allow access to the photo library for selecting images</string>
<key>NSCameraUsageDescription</key>
<string>Allow access to the camera for capturing images</string>
Import react-native-image-crop-picker
In the JavaScript file where you want to implement the image crop picker, import the ImagePicker
library from the react-native-image-crop-picker
:
import ImagePicker from 'react-native-image-crop-picker';
Implement image selection and cropping
Create a function that will handle image selection and cropping. We will use the openPicker
, openCamera
, and openCropper
functions provided by the react-native-image-crop-picker
. These functions open the photo library or camera and allow users to select or capture images.
Gallery image
We will use the openPicker
method provided by the library. It requires an options object and a callback function as parameters:
options
: An object that specifies the options for the image picker. Some commonly used options include:cropping
(boolean): Determines whether to enable image cropping. Set it totrue
to enable cropping.cropperToolbarTitle
(string): The title of the cropping screen's toolbar.includeBase64
(boolean): Determines whether to include the base64 representation of the selected image in the response. Set it totrue
if you need the base64 data.cropperCircleOverlay
(boolean): Determines whether to display a circular cropping overlay. Set it totrue
to enable circular cropping.cropperToolbarWidgetColor
(string): The color of the cropping screen's toolbar widgets.
callback
: A callback function that will be invoked with the response from the image picker. It takes a single parameter,response
, which contains information about the image. Theresponse
object may have the following properties:path
(string): The local path of the selected and cropped image.data
(string): The base64 representation of the selected and cropped image.width
(number): The width of the selected and cropped image.height
(number): The height of the selected and cropped image.
Here’s an example:
const handleImagePicker = () => {
ImagePicker.openPicker({
width,
height,
cropping: true,
})
.then((image) => {
setSelectedImage(image.path);
setHeight(height);
setWidth(width);
console.log(image);
})
.catch((error) => {
console.log(error);
});
};
Code explanation
Here is a line by line explanation of the code above:
Line 1: The
handleImagePicker
function is defined to handle the image picking process.Line 2: The
ImagePicker.openPicker
method is called, which opens the gallery for image selection.Line 3–5: The
openPicker
method takes is provided options object with parameters such aswidth
,height
, andcropping
to specify the desired image dimensions. Thecropping
is set totrue
.Line 7–11: Once an image is selected, the promise returned by the
openPicker
is resolved, and thethen
block is executed. In thethen
block, the selected image's path is stored using thesetSelectedImage
function, and the specifiedwidth
andheight
are set using the respectivesetHeight
andsetWidth
functions.Line 13–15: If any errors occur during the image picking process, the
catch
block is executed, and the error is logged to the console.
Image from camera
We will use the openPicker
method provided by the library. It also requires an options object and a callback function as parameters.
const handleCameraPicker = () => {
ImagePicker.openCamera({
width,
height,
cropping: true,
})
.then((image) => {
setSelectedImage(image.path);
setHeight(height);
setWidth(width);
})
.catch((error) => {
console.log(error);
});
};
Code explanation
Here is the line by line explanation of the code above:
Line 1: The
handleCameraPicker
function is defined to handle the image picking process from the camera.Line 2: The
ImagePicker.openCamera
method is called, which opens the camera for image capture.Line 3–5: The
openCamera
method takes an object with parameters such aswidth
,height
, andcropping
to specify the desired image dimensions and whether cropping should be enabled.Lines 7–11: Once an image is captured, the promise returned by
openCamera
is resolved, and thethen
block is executed. In thethen
block, the captured image's path is stored using thesetSelectedImage
function, and the specifiedwidth
andheight
are set using the respectivesetHeight
andsetWidth
functions.Lines 12–14: If any errors occur during the image picking process, the
catch
block is executed, and the error is logged to the console.
Image cropper
We will use the openPicker
method provided by the library. It also requires an options object and a callback function as parameters.
const handleCropImage = () => {
if (selectedImage) {
ImagePicker.openCropper({
path: selectedImage,
width,
height,
cropping: true,
cropperCircleOverlay: false, // Set to true if you want a circular crop
freeStyleCropEnabled: true,
})
.then((image) => {
setSelectedImage(image.path);
setHeight(250);
setWidth(170);
console.log(image);
})
.catch((error) => {
console.log(error);
});
}
};
Code explanation
Here is the line by line explanation of the code above:
Line 1: The
handleCropImage
function is defined to handle the image cropping process. It first checks if an image is selected to crop.Lines 2–3: If a
selectedImage
is available, theImagePicker.openCropper
method is called, which opens the image crop picker with the specified parameters.Line 4: The
path
parameter is set to theselectedImage
path, indicating the image to be cropped.Lines 5–6: The
width
andheight
parameters define the desired dimensions of the cropped image.Line 7: The
cropping
parameter is set totrue
, enabling the cropping functionality.Line 8: The
cropperCircleOverlay
parameter is set tofalse
, indicating that the crop overlay should be rectangular (set totrue
for a circular crop).Line 9: The
freeStyleCropEnabled
parameter is set totrue
, allowing the user to freely adjust the crop area.Lines 11–16: Once the image is cropped, the promise returned by
openCropper
is resolved, and thethen
block is executed. In thethen
block, the path of the cropped image is stored using thesetSelectedImage
function, and theheight
andwidth
values are updated accordingly.Lines 17–19: If any errors occur during the cropping process, the
catch
block is executed, and the error is logged to the console.
Step 5: Trigger the image crop picker
To trigger the image crop picker, call the handler functions created in the previous step. You can attach them to a button onPress
event or any other user interaction in your app’s
<Button title="Choose from Library" onPress={handleImagePicker} />
<Button title="Take a Photo" onPress={handleCameraPicker} />
{selectedImage && <Button title="Crop Image" onPress={handleCropImage} />}
When the user taps the buttons, the respective image crop picker will open, allowing them to choose an image from the photo library or take a new photo with the camera. The selected image will be cropped based on the specified dimensions, and you can further process the cropped image path as needed in your application.
Example app
Here is a React Native app that allows users to pick cropped images from a gallery or crop after directly capturing using a camera:
import React, { useState } from 'react';import { View, Button, Image, StyleSheet } from 'react-native';import ImagePicker from 'react-native-image-crop-picker';const App = () => { const [selectedImage, setSelectedImage] = useState(null); const [width, setWidth] = useState(350); const [height, setHeight] = useState(500); const handleImagePicker = () => { ImagePicker.openPicker({ width, height, cropping: true, }) .then((image) => { setSelectedImage(image.path); setHeight(height); setWidth(width); console.log(image); }) .catch((error) => { console.log(error); }); }; const handleCameraPicker = () => { ImagePicker.openCamera({ width, height, cropping: true, }) .then((image) => { setSelectedImage(image.path); setHeight(height); setWidth(width); }) .catch((error) => { console.log(error); }); }; const handleCropImage = () => { if (selectedImage) { ImagePicker.openCropper({ path: selectedImage, width, height, cropping: true, cropperCircleOverlay: false, // Set to true if you want a circular crop freeStyleCropEnabled: true, }) .then((image) => { setSelectedImage(image.path); setHeight(250); setWidth(170); console.log(image); }) .catch((error) => { console.log(error); }); } }; return ( <View style={{ flex: 1, justifyContent: 'center', alignItems:'center' }}> {selectedImage && (<Image source={{ uri: selectedImage }} style={{width: width, height: height, marginVertical: 20}} /> )} <View style={{ marginTop: 20 }}> <Button title="Choose from Gallery" onPress={handleImagePicker} /> </View> <View style={{ marginTop: 20 }}> <Button title="Take a Photo" onPress={handleCameraPicker} /> </View> <View style={{ marginTop: 20,marginBottom: 50 }}> {selectedImage && <Button title="Crop Image" onPress={handleCropImage} />} </View> </View> );};export default App;
Here is what the app looks like:
Copyright ©2024 Educative, Inc. All rights reserved