react-nativecameracompressionexpomedia-library

How to compress picture just taken with React Native Expo


I'm using the Camera component from expo and MediaLibrary to save the picture taken. My question is, how can I compress that image when saving it with MediaLibrary in the Galery? Im trying to compress it because later I will also be uploading that image to Firebase Storage. So far this is the code that I have right now working without compressing it:

import React, { useState, useEffect} from 'react';
import { Text, View, TouchableOpacity } from 'react-native';
import { Camera } from 'expo-camera';
import * as MediaLibrary from 'expo-media-library';
import { Dimensions } from 'react-native';
const {height, width} = Dimensions.get('window');

export default function App() {

  const [hasPermission, setHasPermission] = useState(null);
  const [cameraRef, setCameraRef] = useState(null)
  const [type, setType] = useState(Camera.Constants.Type.back);
  useEffect(() => {
    (async () => {
      const { status } = await Camera.requestPermissionsAsync();
      MediaLibrary.requestPermissionsAsync();
      setHasPermission(status === 'granted');
    })();
  }, []);

  if (hasPermission === null) {
    return <View />;
  }

  if (hasPermission === false) {
    return <Text>No access to camera</Text>;
  }

  return (
    <View style={{ flex: 1 }}>
      <Camera style={{ flex: 1 }} type={type} ref={ref => {
        setCameraRef(ref) ;
      }}>
        <View
          style={{
            flex: 1,
            backgroundColor: 'transparent',
            justifyContent: 'flex-end'
          }}>
          <TouchableOpacity style={{alignSelf: 'center', marginBottom: 20}} onPress={async() => {
            if(cameraRef){
              let photo = await cameraRef.takePictureAsync({ skipProcessing: true });
              MediaLibrary.saveToLibraryAsync(photo.uri);
            }
          }}>
            <View style={{ 
              borderWidth: 2,
              borderColor: 'white',
              height: 50,
              width:50,
              display: 'flex',
              justifyContent: 'center',
              alignItems: 'center',
              borderRadius: 25,
              }}
            >
              <View style={{
                borderWidth: 2,
                borderColor: 'white',
                height: 40,
                width:40,
                backgroundColor: 'white',
                borderRadius: 25}} >
              </View>
            </View>
          </TouchableOpacity>
        </View>
      </Camera>
    </View>
  );
}

Solution

  • ImageManipulator comes with expo, you can compress, resize, rotate, crop and many more.

    import { ImageManipulator } from 'expo';
    
    const manipResult = await ImageManipulator.manipulate(
        imageUri,
        [{ resize: { width: 640, height: 480 } }],
        { format: 'jpg' }
    );
    

    Checkout https://docs.expo.io/versions/latest/sdk/imagemanipulator/