Background Removal API – remove.bg

I want to use remove.bg's api in my app. I made a request through python and it works, but I do not know how to transfer this to appinventor. My python code and the file I used are attached.
edit: I am not sure whether the image I found online can be used for free, so I removed it.

import requests

response = requests.post(

'https://api.remove.bg/v1.0/removebg',

files={'image_file': open('dwayne.jpg', 'rb')},

data={'size': 'auto'},

headers={'X-Api-Key': 'API-KEY-HERE'},

)

if response.status_code == requests.codes.ok:

with open('no-bg.png', 'wb') as out:

    out.write(response.content)

else:

print("Error:", response.status_code, response.text)

If you can find the same code in JavaScript, that would be easier to combine with your App Inventor App.

Do you have a License to use that image of Dwayne Johnston? If not, please remove it from your Post.

Thank you for replying. I got the image from a google search. A reverse image search and some checking on getty images tells me that it's free for non commercial use. On the api's website, I found both node JS and java code. I will post both as I am not sure which is better for this situation.

java

// Requires "Apache HttpComponents" to be installed (see hc.apache.org)

Response response = Request.Post("https://api.remove.bg/v1.0/removebg")
    .addHeader("X-Api-Key", "INSERT_YOUR_API_KEY_HERE")
    .body(
        MultipartEntityBuilder.create()
        .addBinaryBody("image_file", new File("/path/to/file.jpg"))
        .addTextBody("size", "auto")
        .build()
    ).execute();
response.saveContent(new File("no-bg.png"));

node.js

// Requires "axios" and "form-data" to be installed (see https://www.npmjs.com/package/axios and https://www.npmjs.com/package/form-data)
const axios = require('axios');
const FormData = require('form-data');
const fs = require('fs');
const path = require('path');

const inputPath = '/path/to/file.jpg';
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': 'INSERT_YOUR_API_KEY_HERE',
  },
  encoding: null
})
.then((response) => {
  if(response.status != 200) return console.error('Error:', response.status, response.statusText);
  fs.writeFileSync("no-bg.png", response.data);
})
.catch((error) => {
    return console.error('Request failed:', error);
});

The Java might be good for someone to build an App Inventor extension, but your App has to have an internet connection.

We can make a post request in App Inventor via the Web component, so that is worth experimenting with.

Re Dwayne, I only see a commercial license for his photographs on Getty Images. Getty are not the owners of the copyright, they are resellers.

I have tried to use the post block in the web component, but I only get a 404 error. So either I am doing something wrong, or it just does not work.

As for Dwayne, the getty images site was not very clear whether I could use the image. I got this info from their help center. For now I will use another image
Using images for free

The images on Getty Images are intended for use in commercial and editorial projects. This means you need to buy a license to use the image in most projects, including personal use.

You can use an image without paying for a license with our Embed feature, which lets you use over 70 million photos on any non-commercial website or blog (if you're using it to sell a product, raise money or promote or endorse something, Embed isn't for you). Just do a search, then go to Filters to turn on the Embeddable images filter on the search results page.

If you post you test code here, someone who knows more about it than me can help you. Probably the critical issue is where the image is stored and where the modified image should be stored. Possibly only an Android shared directory can be used.

the image above is the code I used. As far as I know, when the image is returned, setting the image1.picure to the filename variable should work, assuming there is an image there.
@ChrisWard Thank you for your help!

Plonk a Label or TextBox on your Screen and populate it with all the result values from Web1 Got File.

The gotfile event does not trigger at all, but the gottext event returns Do It Result: Do It Result: "< !DOCTYPE html >
< html lang="en" >
< head >
< meta charset="utf-8" >
< title > Error < /title >
< /head >
< body >
< pre >Cannot POST /v1.0/removebg/image_file=dwayne.jpg< /pre >
< /body >
< /html >

where on your device is dwayne.jpg?

it is uploaded in the media section of appinventor

Right - that's a private directory, anything outside of the App cannot access it, so that is probably the first hurdle that the Cannot Post message is moaning about.

So the image needs to be in Shared Storage '/Pictures' and likely requires the full path to it:

/storage/emulated/0/Pictures (That's a zero)

ok, I'll try that, thanks!

I cannot find this folder on my amazon fire tablet. I have checked everywhere but I cannot find the storage folder. Could you tell me where it is?

The remove.bg API will not work in App Inventor currently...

Thought I would have a look at this, but above my pay grade :wink:

Problems in red, any suggestions?

Code
import com.google.appinventor.components.annotations.SimpleFunction;
import com.google.appinventor.components.runtime.AndroidNonvisibleComponent;
import com.google.appinventor.components.runtime.ComponentContainer;

import org.apache.http.entity.mime.*;

public class RemoveBackground extends AndroidNonvisibleComponent {

  public RemoveBackground(ComponentContainer container) {
    super(container.$form());
  }

  @SimpleFunction(description = "Removes background of Image")
  // Requires "Apache HttpComponents" to be installed (see hc.apache.org)
  public void Remove(String filename, String apiKey) {
  Response response = Request.Post("https://api.remove.bg/v1.0/removebg")
          .addHeader("X-Api-Key", apiKey)
          .body(
                  MultipartEntityBuilder.create()
                          .addBinaryBody("image_file", new File(filename))
                          .addTextBody("size", "auto")
                          .build()
          ).execute();
  response.saveContent(new File("no-bg.png"));
  }
}

It is because you did not import the relevant classes currently.

import java.io.File;
import org.omg.CORBA.Request;
import javax.ws.rs.core.Response;

Yes, I was offered three alternative classes for "Response" :wink: Thank you.

Hmmmm

Probably have to do a file inputstream / outputstream to save the file.

I believe the answer is in here

or here

somewhere....

or here:

2 Likes

I think that tablet could be trouble. In the past Amazon have strayed from the Android standards. Let's see if TimAI2 can build an extension.

Good news (?) Google are releasing a tablet-specific version of Android later this year.

Do you think it will work with a samsung galaxy xs6 lite?