GithubHelp home page GithubHelp logo

mtownsend5512 / remove-bg Goto Github PK

View Code? Open in Web Editor NEW
170.0 12.0 29.0 17 KB

Programmatically remove backgrounds from your images using the remove.bg api

License: MIT License

PHP 100.00%
remove bg background php laravel transparent png api

remove-bg's Introduction

Programmatically remove backgrounds from your images using the remove.bg api.

Installation

Install via composer:

composer require mtownsend/remove-bg

This package is designed to work with any PHP 7.0+ application but has special support for Laravel.

Registering the service provider (Laravel users)

For Laravel 5.4 and lower, add the following line to your config/app.php:

/*
 * Package Service Providers...
 */
Mtownsend\RemoveBg\Providers\RemoveBgServiceProvider::class,

For Laravel 5.5 and greater, the package will auto register the provider for you.

Using Lumen

To register the service provider, add the following line to app/bootstrap/app.php:

$app->register(Mtownsend\RemoveBg\Providers\RemoveBgServiceProvider::class);

Publishing the config file (Laravel users)

php artisan vendor:publish --provider="Mtownsend\RemoveBg\Providers\RemoveBgServiceProvider"

Once your removebg.php has been published your to your config folder, add the api key you obtained from Remove.bg. If you are using Laravel and put your remove.bg api key in the config file, Laravel will automatically set your api key every time you instantiate the class through the helper or facade.

Quick start

Using the class

use Mtownsend\RemoveBg\RemoveBg;

$absoluteUrl = 'https://yoursite.com/images/photo.jpg';
$pathToFile = 'images/avatar.jpg';
$base64EncodedFile = base64_encode(file_get_contents($pathToFile));

$removebg = new RemoveBg($apiKey);

// Directly saving files
$removebg->url($absoluteUrl)->save('path/to/your/file.png');
$removebg->file($pathToFile)->save('path/to/your/file2.png');
$removebg->base64($base64EncodedFile)->save('path/to/your/file3.png');

// Getting the file's raw contents to save or do something else with
$rawUrl = $removebg->url($absoluteUrl)->get();
$rawFile = $removebg->file($pathToFile)->get();
$rawBase64 = $removebg->base64($base64EncodedFile)->get();

file_put_contents('path/to/your/file4.png', $rawUrl);
// etc...

// Getting the file's base64 encoded contents from the api
$base64Url = $removebg->url($absoluteUrl)->getBase64();
$base64File = $removebg->file($pathToFile)->getBase64();
$base64Base64 = $removebg->base64($base64EncodedFile)->getBase64();

file_put_contents('path/to/your/file5.png', base64_decode($base64Url));
// etc...

// Please note: remove.bg returns all images in .png format, so you should be saving all files received from the api as .png.

Advanced usage

Remove.bg offers several request body parameters for each api call. For an up to date list, you should always check the remove.bg api documentation.

Here is an example of an api call configured with specific request body parameters.

$removebg = new RemoveBg($apiKey);

// Directly saving files
$removebg->url($absoluteUrl)
->body([
    'size' => '4k', // regular, medium, hd, 4k, auto
    'bg_color' => '#CBD5E0',
    'add_shadow' => true, // primarily used for automotive photos as of the time this documentation was written
    'channels' => 'rgba', // rgba, alpha
])
->save('path/to/your/file.png');

You may also directly specify request header parameters. As of right now this does not appear to offer much functionality in terms of how the Remove.bg api will consume these headers, but we thought it was important to expose this functionality. Consider the following example:

$removebg = new RemoveBg($apiKey);

// Directly saving files
$removebg->url($absoluteUrl)
->headers([
    'X-Foo-Header' => 'Some Bar Value',
    'X-Foo-Header-2' => 'Some Bar Value 2',
])
->save('path/to/your/file.png');

Account details

The Remove.bg api offers an endpoint to check your account's credit balance and free api call usage. If your application needs to check your available credits before processing images this package makes it an absolute breeze!

The following code example is how you can programmatically check your account information. Note, the account method has one optional argument: $getResponseAsObject = true. By default your response will be returned as an object. You can return the response as an associative array by passing false to the account(false) method.

$removebg = new RemoveBg($apiKey);

$account = $removebg->account();

// $account will be something like this:
{
  "data": {
    "attributes": {
      "credits": {
        "total": 200,
        "subscription": 150,
        "payg": 50
      },
      "api": {
        "free_calls": 50,
        "sizes": "all"
      }
    }
  }
}

To access your total credits you could do so like this: $account->data->attributes->credits->total.

A practical example could look something like the following:

$removebg = new RemoveBg($apiKey);

$account = $removebg->account();

if ($account->data->attributes->credits->total >= 1) {
	$removebg->url($absoluteUrl)->save('path/to/your/file.png');
}

Using the global helper (Laravel users)

If you are using Laravel, this package provides a convenient helper function which is globally accessible.

removebg()->url($absoluteUrl)->save(public_path('path/to/your/file.png'));

Using the facade (Laravel users)

If you are using Laravel, this package provides a facade. To register the facade add the following line to your config/app.php under the aliases key.

'RemoveBg' => Mtownsend\RemoveBg\Facades\RemoveBg::class,
use RemoveBg;

RemoveBg::file($pathToFile)->save(public_path('path/to/your/file.png'));

Credits

Testing

Tests coming soon...

You can run the tests with:

./vendor/bin/phpunit

License

The MIT License (MIT). Please see License File for more information.

remove-bg's People

Contributors

mtownsend5512 avatar skalero01 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  avatar  avatar  avatar  avatar  avatar  avatar  avatar

remove-bg's Issues

Sending the fatal errors when credits ends in the account

Hello, Hope you are doing great

We have an issue, when have integrated the API into our project. During development we found an issue, our credits ends and it throw the errors while it should send errors in the response.

We have use below code to remove background

$removebg = new RemoveBg($this->apiKey); $response = $removebg->file($image_url)->save($targetFile);

error

It should send back the response, so we can show specific message to our users in case of credits goes to 0

Is there any solution for that ?

Thanks

API changes

A note to self:

  • JSON responses: The "/removebg.json" endpoint has been integrated into the regular "/removebg" endpoint with an HTTP Accept header of "application/json".

Guzzle 7 support

Can we support guzzle 7? Laravel latest installation requires guzzle 7 and above.

Error: array_merge(): Argument #2 is not an array

array_merge is being called here: https://github.com/mtownsend5512/remove-bg/blob/master/src/RemoveBg.php#L231

Version: mtownsend/remove-bg (1.2.0)

Code to reproduce:

<?php

use Mtownsend\RemoveBg\RemoveBg;

$removebg = new RemoveBg(getenv('REMOVEBG_KEY'));
$removebg->file('/Users/bogus/foo.jpg')
    ->save('/Users/bogus/foo_'.uniqid().'.jpg');

It seems src/RemoveBg.php doesn't initialize $data at line 205 (https://github.com/mtownsend5512/remove-bg/blob/master/src/RemoveBg.php#L205).

The following change fixed it for me:

    protected function formatBody()
    {
        switch ($this->imageFormat) {
            case 'image_file':
                $index = 0;
                $data = []; // <==== add this line
                foreach ($this->body as $key => $value) {
                    $data[$index]['name'] = $key;
                    $data[$index]['contents'] = $value;
                    $index++;
                }
                break;
            default:
                $data = $this->body;
        }
        return $data;
    }

Am I missing something or is it really a bug?

Thx

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.