Coder Social home page Coder Social logo

remove.bg's Introduction

remove.bg API wrapper for Node.js

NPM version Downloads Twitter Follow

The AWESOME remove.bg API is quite easy to use, but it can always be easier - that's where this package comes in.

Requirements

Get your API key from the remove.bg website. At the moment it's early access, so it may take some time to get yours.

Installation

npm i remove.bg

Examples

Look at the various removeFrom*.ts files in the examples folder, or check out the snippets below.

API

The common input parameters of all three currently supported removeBackgroundFrom* functions are:

Only the apiKey property is mandatory.

Property Type Description
apiKey string The API key you got from the remove.bg website.
size "preview" (same as "small" or "regular"), "full" (same as "4k"), "medium", "hd", "auto" The returned size of the image. The cheaper "preview" option is default, while "auto" uses the highest available resolution (based on image size and available credits.
type "auto", "person", "product", "car" Help the API a little by telling the type of image you want to extract the background from. Default "auto".
format "auto", "png", "jpg", "zip" Result image format, the default is "auto" which produces a .png if transparentcy is detected and .jpg otherwise.
scale string Scales the subject relative to the total image size. Can be any value from "10%" to "100%", or "original" (default). Scaling the subject implies "position=center" (unless specified otherwise).
position string Positions the subject within the image canvas. Can be "original" (default unless "scale" is given), "center" (default when "scale" is given) or a value from "0%" to "100%" (both horizontal and vertical) or two values (horizontal, vertical).
crop boolean Whether to crop off all empty regions (default: false). Note that cropping has no effect on the amount of charged credits.
crop_margin string Adds a margin around the cropped subject (default: 0). Can be an absolute value (e.g. "30px") or relative to the subject size (e.g. "10%"). Can be a single value (all sides), two values (top/bottom and left/right) or four values (top, right, bottom, left). This parameter only has an effect when crop is true.
roi string Region of interest: Only contents of this rectangular region can be detected as foreground. Everything outside is considered background and will be removed. The rectangle is defined as two x/y coordinates in the format "<x1> <y1> <x2> <y2>". The coordinates can be in absolute pixels (suffix 'px') or relative to the width/height of the image (suffix '%'). By default, the whole image is the region of interest ("0% 0% 100% 100%").
bg_color string Adds a solid color background. Can be a hex color code (e.g. "81d4fa", "fff") or a color name (e.g. "green"). For semi-transparency, 4-/8-digit hex codes are also supported (e.g. "81d4fa77"). (If this parameter is present, the other "bg_" parameters must be empty.)
bg_image_url string Adds a background image from a URL. The image is centered and resized to fill the canvas while preserving the aspect ratio, unless it already has the exact same dimensions as the foreground image. (If this parameter is present, the other "bg_" parameters must be empty.)
outputFile string The path to save the returned file to. Alternatively, you can access the result via the result object's base64img property (see below).
channels string Request either the finalized image ("rgba", default) or an alpha mask ("alpha"). Note: Since remove.bg also applies RGB color corrections on edges, using only the alpha mask often leads to a lower final image quality. Therefore "rgba" is recommended.
add_shadow boolean Whether to add an artificial shadow to the result (default: false). NOTE: Adding shadows is currently only supported for car photos. Other subjects are returned without shadow, even if set to true (this might change in the future).

And the output properties are:

Property Type Description
base64img string Base64 encoded representation of the returned image.
detectedType string Either person, product, animal, car, or other.
creditsCharged number Amount of credits charged for this call, based on the output size of the response.
resultWidth number The width of the result image, in pixels.
resultHeight number The height of the result image, in pixels.
rateLimit number Total rate limit in megapixel images.
rateLimitRemaining number Remaining rate limit for this minute.
rateLimitReset number Unix timestamp when rate limit will reset.
retryAfter number Seconds until rate limit will reset (only present if rate limit exceeded).

removeBackgroundFromImageFile

Remove the background from a local file.

import { RemoveBgResult, RemoveBgError, removeBackgroundFromImageFile } from "remove.bg";

const localFile = "./local/file/name.jpg";
const outputFile = `${__dirname}/out/img-removed-from-file.png`;

removeBackgroundFromImageFile({
  path: localFile,
  apiKey: "YOUR-API-KEY",
  size: "regular",
  type: "auto",
  scale: "50%",
  outputFile
}).then((result: RemoveBgResult) => {
 console.log(`File saved to ${outputFile}`);
  const base64img = result.base64img;
}).catch((errors: Array<RemoveBgError>) => {
 console.log(JSON.stringify(errors));
});

Or have a cool async/await example to please your inner hipster:

async function myRemoveBgFunction(path: string, outputFile: string) {
    const result: RemoveBgResult = await removeBackgroundFromImageFile({
      path,
      apiKey: "YOUR-API-KEY",
      size: "regular",
      type: "person",
      crop: true,
      scale: "50%",
      outputFile
    });
}

removeBackgroundFromImageUrl

Remove the background from a remote file (URL).

import { RemoveBgResult, RemoveBgError, removeBackgroundFromImageUrl } from "remove.bg";

const url = "https://domain.tld/path/file.jpg";
const outputFile = `${__dirname}/out/img-removed-from-file.png`;

removeBackgroundFromImageUrl({
  url,
  apiKey: "YOUR-API-KEY",
  size: "regular",
  type: "person",
  outputFile
}).then((result: RemoveBgResult) => {
 console.log(`File saved to ${outputFile}`);
  const base64img = result.base64img;
}).catch((errors: Array<RemoveBgError>) => {
 console.log(JSON.stringify(errors));
});

removeBackgroundFromImageBase64

Remove the background from a base64 encoded file.

import { RemoveBgResult, RemoveBgError, removeBackgroundFromImageBase64 } from "remove.bg";
import * as fs from "fs";

const localFile = "./local/file/name.jpg";
const base64img = fs.readFileSync(localFile, { encoding: "base64" });
const outputFile = `${__dirname}/out/img-removed-from-file.png`;

removeBackgroundFromImageBase64({
  base64img,
  apiKey: "YOUR-API-KEY",
  size: "regular",
  type: "product",
  outputFile
}).then((result: RemoveBgResult) => {
 console.log(`File saved to ${outputFile}`);
  const base64img = result.base64img;
}).catch((errors: Array<RemoveBgError>) => {
 console.log(JSON.stringify(errors));
});

remove.bg's People

Contributors

eddyverbruggen avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar

remove.bg's Issues

Add more parameters to API wrapper

Hi Eddy,

First, I'd like to thank you for creating this library.

Could you please add the following parameters to the API:

roi

(string)

Region of interest: Only contents of this rectangular region can be detected as foreground. Everything outside is considered background and will be removed. The rectangle is defined as two x/y coordinates in the format " ". The coordinates can be in absolute pixels (suffix 'px') or relative to the width/height of the image (suffix '%'). By default, the whole image is the region of interest ("0% 0% 100% 100%").

crop

(boolean)

Whether to crop off all empty regions (default: false). Note that cropping has no effect on the amount of charged credits.

crop_margin

(string)

Adds a margin around the cropped subject (default: 0). Can be an absolute value (e.g. "30px") or relative to the subject size (e.g. "10%"). Can be a single value (all sides), two values (top/bottom and left/right) or four values (top, right, bottom, left). This parameter only has an effect when "crop=true". The maximum margin that can be added on each side is 50% of the subject dimensions or 500 pixels.

format

(string)

Result image format: "auto" = Use PNG format if transparent regions exists, otherwise use JPG format (default), "png" = PNG format with alpha transparency, "jpg" = JPG format, no transparency, "zip" = ZIP format, contains color image and alpha matte image, supports transparency (recommended).

bg_color

(string)

Adds a solid color background. Can be a hex color code (e.g. 81d4fa, fff) or a color name (e.g. green). For semi-transparency, 4-/8-digit hex codes are also supported (e.g. 81d4fa77). (If this parameter is present, the other bg_ parameters must be empty.)

bg_image_url

(string)

Adds a background image from a URL. The image is centered and resized to fill the canvas while preserving the aspect ratio, unless it already has the exact same dimensions as the foreground image. (If this parameter is present, the other bg_ parameters must be empty.)

Regards,

TypeError: Invalid value "undefined" for header "Content-Length"

I get this error when trying to use this package

TypeError: Invalid value "undefined" for header "Content-Length"
    at ClientRequest.setHeader (node:_http_outgoing:579:3)
    at FormData.<anonymous> (C:\Users\Olalekan\Documents\GitHub\Seedvendue-server\node_modules\unirest\node_modules\form-data\lib\form_data.js:321:13)
    at C:\Users\Olalekan\Documents\GitHub\Seedvendue-server\node_modules\unirest\node_modules\form-data\lib\form_data.js:265:7
    at C:\Users\Olalekan\Documents\GitHub\Seedvendue-server\node_modules\async\lib\async.js:251:17
    at done (C:\Users\Olalekan\Documents\GitHub\Seedvendue-server\node_modules\async\lib\async.js:126:15)
    at C:\Users\Olalekan\Documents\GitHub\Seedvendue-server\node_modules\async\lib\async.js:32:16
    at C:\Users\Olalekan\Documents\GitHub\Seedvendue-server\node_modules\async\lib\async.js:248:21
    at C:\Users\Olalekan\Documents\GitHub\Seedvendue-server\node_modules\async\lib\async.js:572:34
    at C:\Users\Olalekan\Documents\GitHub\Seedvendue-server\node_modules\unirest\node_modules\form-data\lib\form_data.js:105:13
    at FSReqCallback.oncomplete (node:fs:198:21)
images.forEach(async (image) => {
        const bgRemove = await this.bgRemover.RemoveBgFunction(
          `./upload/products/${image.filename}`,
          `./upload/products/${image.filename}`,
        );
export class BgRemover {
  constructor(private readonly config: ConfigService) {}

  async RemoveBgFunction(
    path: string,
    outputFile: string,
  ): Promise<object> | null {
    try {
      const result: RemoveBgResult = await removeBackgroundFromImageFile({
        path,
        apiKey: this.config.get('BG_REMOVER_API'),
        size: 'regular',
        crop: false,
        scale: '50%',
        outputFile,
      });

      return { result: result, status: true };
    } catch (error) {
      console.log(error);
      return null;
    }
  }
}

Uncaught ReferenceError: exports is not defined

I got this error

Uncaught ReferenceError: exports is not defined
    at Module../node_modules/remove.bg/dist/index.js (index.js:33)

my environment is ruby on rails 6 with rails webpacker

my babel config

module.exports = function(api) {
  var validEnv = ['development', 'test', 'production']
  var currentEnv = api.env()
  var isDevelopmentEnv = api.env('development')
  var isProductionEnv = api.env('production')
  var isTestEnv = api.env('test')

  if (!validEnv.includes(currentEnv)) {
    throw new Error(
      'Please specify a valid `NODE_ENV` or ' +
        '`BABEL_ENV` environment variables. Valid values are "development", ' +
        '"test", and "production". Instead, received: ' +
        JSON.stringify(currentEnv) +
        '.'
    )
  }

  return {
    presets: [
      isTestEnv && [
        '@babel/preset-env',
        {
          targets: {
            node: 'current'
          },
          modules: 'commonjs'
        },
        '@babel/preset-react'
      ],
      (isProductionEnv || isDevelopmentEnv) && [
        '@babel/preset-env',
        {
          forceAllTransforms: true,
          useBuiltIns: 'entry',
          corejs: 3,
          modules: false,
          exclude: ['transform-typeof-symbol']
        }
      ],
      [
        '@babel/preset-react',
        {
          development: isDevelopmentEnv || isTestEnv,
          useBuiltIns: true
        }
      ]
    ].filter(Boolean),
    plugins: [
      'babel-plugin-macros',
      '@babel/plugin-syntax-dynamic-import',
      isTestEnv && 'babel-plugin-dynamic-import-node',
      '@babel/plugin-transform-destructuring',
      [
        '@babel/plugin-proposal-class-properties',
        {
          loose: true
        }
      ],
      [
        '@babel/plugin-proposal-object-rest-spread',
        {
          useBuiltIns: true
        }
      ],
      [
        '@babel/plugin-transform-runtime',
        {
          helpers: false,
          regenerator: true,
          corejs: false
        }
      ],
      [
        '@babel/plugin-transform-regenerator',
        {
          async: false
        }
      ],
      isProductionEnv && [
        'babel-plugin-transform-react-remove-prop-types',
        {
          removeImport: true
        }
      ]
    ].filter(Boolean)
  }
}

package.json

{
  "name": "event",
  "private": true,
  "dependencies": {
    "@babel/preset-react": "^7.12.13",
    "@fortawesome/fontawesome-free": "^5.15.2",
    "@rails/actioncable": "^6.0.0",
    "@rails/activestorage": "^6.0.0",
    "@rails/ujs": "^6.0.0",
    "@rails/webpacker": "5.2.1",
    "@tensorflow-models/body-pix": "^2.1.0",
    "@tensorflow/tfjs": "^3.3.0",
    "@tensorflow/tfjs-converter": "^3.3.0",
    "@tensorflow/tfjs-core": "^3.3.0",
    "@zoomus/websdk": "^1.9.1",
    "babel-plugin-transform-react-remove-prop-types": "^0.4.24",
    "bootstrap": "^4.6.0",
    "bs-stepper": "^1.7.0",
    "jquery": "^3.5.1",
    "jquery.countdown": "^1.2.8",
    "popper.js": "^1.16.1",
    "prop-types": "^15.7.2",
    "react": "^17.0.1",
    "react-dom": "^17.0.1",
    "react-webcam": "^5.2.3",
    "remove.bg": "^1.3.0",
    "stimulus": "^2.0.0",
    "turbolinks": "^5.2.0",
    "webcam-easy": "^1.0.5"
  },
  "version": "0.1.0",
  "devDependencies": {
    "webpack-dev-server": "^3.11.2"
  }
}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.