How to Compress or Manipulate Images in React Native Expo

How to Compress or Manipulate Images in React Native Expo

Post by: Niraj Dhungana

Posted on: Nov 13, 2021

#React Native# Expo

Nowadays smartphone cameras are a beast. A normal picture clicked with my smartphone becomes 4MB. And if I were just a normal user this would not be a topic of discussion but because I am a programmer it costs my cloud storage.

So, in this small post I will teach you guys how we can compress the Image size in React Native Expo.

For that you don’t need to do any special coding because expo has a cool npm package which we can use to decrease or compress image size.

Which Package to Use

Inside the expo we have an expo-image-manipulator which we can use to compress image size and also for other manipulations as well like flip, rotate, crop etc. If you want more information on it then you can go to this link.

You can also use it if you are using bare-react-native cli but for that you need to go some extra miles and unfortunately I am not covering that here. You can visit this link if you are using bare-react-native.

First we need to install: expo-image-manipulator. For that you can run this command. 

1
expo install expo-image-manipulator

After installing it we need to import everything as ImageManipulator like below.

1
2
3
import * as ImageManipulator from 'expo-image-manipulator';

const file = await ImageManipulator.manipulateAsync(img.uri, [], { compress: 0.5 });

To manipulate images using expo-image-manipulator it provides the manipulateAsync method. Which is an asynchronous method. It takes three arguments. The actual image uri goes first, actions goes second and save options at the end.

1
await ImageManipulator.manipulateAsync(uri, actions, saveOptions)

What Kind of Images it Can Manipulate

It does not take the image files from outside. So make sure you are using URI from the local file system not from the remote api link. Means you can only use the image files which you read from the device storage.

Actions

Action is an array of objects representing manipulation options. We can pass multiple options as objects inside this array. Like we can resize, rotate, flip and crop.

Save Options

After manipulating the image we can also define some options and inside it we can specify the image quality and image format like png or jpg.

1
2
3
4
5
6
7
await ImageManipulator.
manipulateAsync(img.uri, [
{resize: {width: 200, height: 200}},
{rotare: 45},
{flip: ImageManipulator.FlipType.Vertical}
],
{compress: 0.5, format: ImageManipulator.SaveFormat.PNG});

Inside this little example as you can see the first thing that we are passing is image uri, and some action options to resize, rotate and flip the image. And at the end we are passing save options to compressing the image by 50% and converting the image to png format.

You may like this post: How to find out which key is being pressed