0

I'm trying to integrate the remove.bg API into a react native app. However, I'm not sure how to call a node js file from a react native button. Please let me know if I can clarify anything. Thanks for responces!

React Native JS Code containing remove.bg code:

global.Buffer = global.Buffer || require('buffer').Buffer
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');
const { newinputPath } = require('../Wardrobe');

const inputPath = newinputPath;
const formData = new FormData();
formData.append('size', 'auto');
formData.append('image_file', fs.createReadStream(inputPath), path.basename(inputPath));

axios({
method: 'post',
url: 'https://api.remove.bg/v1.0/removebg',
data: formData,
responseType: 'arraybuffer',
headers: {
    ...formData.getHeaders(),
    'X-Api-Key': 'kLJT2Gev5QbZe5epeexwrrKn',
},
encoding: null
})
.then((response) => {
if(response.status != 200) return console.error('Error:', response.status, response.statusText);
fs.writeFileSync("pics/no-bg.png", response.data);
})
.catch((error) => {
    return console.error('Request failed:', error);
});

Front-end code containing button:

import React, { useState, useEffect } from 'react';
import { Button, Image, View, Platform } from 'react-native';
import * as ImagePicker from 'expo-image-picker';

let result;
export let newinputPath;

export default function ImagePickerExample() {
  const [image, setImage] = useState(null);
  const pickImage = async () => {
    // No permissions request is necessary for launching the image library
    result = await ImagePicker.launchImageLibraryAsync({
      mediaTypes: ImagePicker.MediaTypeOptions.All,
      allowsEditing: true,
      aspect: [4, 3],
      quality: 1,
    });
    console.log(result);

    if (!result.canceled) {
      setImage(result.assets[0].uri);
    }
    newinputPath = result.assets[0].uri;
  };
   return (
     <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
       <Button title="Pick an image from camera roll" onPress={pickImage} />
       {image && <Image source={{ uri: image }} style={{ width: 200, height: 200 }} />}
     </View>
   );
}
Mig82
  • 4,856
  • 4
  • 40
  • 63
  • There's not an error. This post is simply asking how one would call a node js file from a onPress function contained in a react native button. Thanks for the comment! – Tre Seibert Dec 03 '22 at 23:58

0 Answers0