PHPackages                             artisan-build/background-remover - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Image &amp; Media](/categories/media)
4. /
5. artisan-build/background-remover

ActiveLibrary[Image &amp; Media](/categories/media)

artisan-build/background-remover
================================

Laravel wrapper for artisan-build/bg-remover

00C++

Since Jan 12Pushed 3mo agoCompare

[ Source](https://github.com/artisan-build/background-remover)[ Packagist](https://packagist.org/packages/artisan-build/background-remover)[ RSS](/packages/artisan-build-background-remover/feed)WikiDiscussions main Synced 1mo ago

READMEChangelogDependenciesVersions (1)Used By (0)

Background Remover for Laravel
==============================

[](#background-remover-for-laravel)

[![MIT Licensed](https://camo.githubusercontent.com/55c0218c8f8009f06ad4ddae837ddd05301481fcf0dff8e0ed9dadda8780713e/68747470733a2f2f696d672e736869656c64732e696f2f62616467652f6c6963656e73652d4d49542d627269676874677265656e2e7376673f7374796c653d666c61742d737175617265)](LICENSE.md)

A Laravel wrapper for the [artisan-build/bg-remover](https://github.com/artisan-build/bg-remover) C++ binary, providing fast and efficient background removal using OpenCV's GrabCut algorithm and optional ML-based segmentation.

Features
--------

[](#features)

- 🚀 **Fast** - Native C++ performance using OpenCV
- 🤖 **ML Support** - Optional ONNX Runtime for ML-based segmentation (U2-Net, RMBG)
- 🎯 **Simple API** - Easy-to-use Laravel service class
- ☁️ **Cloud Storage** - Built-in support for Laravel Storage (S3, local, etc.)
- 📦 **Multi-platform** - Supports Ubuntu (Forge) and macOS ARM64
- 🔒 **Checksum Verification** - Ensures binary integrity
- ⚡ **Queue Support** - Async processing via Laravel queues
- 🔧 **Build from Source** - Includes full C++ source code and build system
- 🎨 **Demo UI** - Interactive web interface for testing

Requirements
------------

[](#requirements)

- PHP 8.2+
- Laravel 11.0+ or 12.0+

Installation
------------

[](#installation)

Install the package via Composer:

```
composer require artisan-build/background-remover
```

Install the binary for your platform:

```
php artisan background-removal:install
```

### Platform Auto-Detection

[](#platform-auto-detection)

The install command automatically detects your platform:

- **Ubuntu/Debian** → `bg-remover-ubuntu-x86_64` (for Laravel Forge, Vapor, etc.)
- **macOS** → `bg-remover-macos-arm64` (for Apple Silicon development)

### Manual Platform Selection

[](#manual-platform-selection)

If auto-detection fails or you need a specific platform:

```
php artisan background-removal:install --platform=ubuntu
php artisan background-removal:install --platform=macos-arm64
```

### Custom Platform Support

[](#custom-platform-support)

The package only maintains binaries for platforms we actively use. For other platforms (Windows, Raspberry Pi, Arch, etc.), see the [FORKING.md](https://github.com/artisan-build/bg-remover/blob/main/FORKING.md) guide to build your own binary.

Quick Install Binary (Standalone)
---------------------------------

[](#quick-install-binary-standalone)

If you're not using Laravel or want to quickly install the binary:

```
# Run the installation script
./install-binary.sh
```

This will auto-detect your platform and download the appropriate binary to `bin/bg-remover`.

Building from Source
--------------------

[](#building-from-source)

This package now includes the complete C++ source code. You can build the binary yourself:

### Quick Build (macOS)

[](#quick-build-macos)

```
# Install OpenCV and ONNX Runtime
brew install opencv onnxruntime

# Build with ML support
cd cpp-src
make ML=1

# Or build without ML support
make

# Install
mkdir -p ../bin
cp bg-remover ../bin/
```

### Quick Build (Ubuntu/Debian)

[](#quick-build-ubuntudebian)

```
# Install dependencies
sudo apt-get update
sudo apt-get install -y g++ make pkg-config libopencv-dev

# Optional: Install ONNX Runtime for ML support
# Follow: https://github.com/microsoft/onnxruntime/releases

# Build with ML support (if ONNX Runtime installed)
cd cpp-src
make ML=1

# Or build without ML support
make

# Install
mkdir -p ../bin
cp bg-remover ../bin/
```

### Docker Builds (Cross-platform)

[](#docker-builds-cross-platform)

```
cd cpp-src

# Build for Ubuntu (includes ML support)
make ubuntu

# Install
mkdir -p ../bin
cp bg-remover-ubuntu-x86_64 ../bin/bg-remover
chmod +x ../bin/bg-remover
```

For detailed build instructions, see [cpp-src/README.md](cpp-src/README.md).

Demo UI
-------

[](#demo-ui)

Try out the background remover with a simple web interface:

1. Install the binary (see above)
2. Start the demo: ```
    cd demo
    php -S localhost:8000
    ```
3. Open  in your browser
4. Upload an image and see the result

The demo features:

- Drag-and-drop image upload
- Side-by-side comparison
- Download processed images
- Support for JPG and PNG

For more details, see [demo/README.md](demo/README.md).

Usage
-----

[](#usage)

### Basic Usage

[](#basic-usage)

```
use ArtisanBuild\BackgroundRemover\Services\BackgroundRemovalService;

$service = app(BackgroundRemovalService::class);

// Remove background from local files
$service->removeBackground(
    inputPath: '/path/to/input.jpg',
    outputPath: '/path/to/output.png'
);
```

### Using Laravel Storage

[](#using-laravel-storage)

```
use ArtisanBuild\BackgroundRemover\Services\BackgroundRemovalService;

$service = app(BackgroundRemovalService::class);

// Remove background using Storage disks
$service->removeBackgroundFromStorage(
    inputDisk: 's3',
    inputPath: 'uploads/photo.jpg',
    outputDisk: 's3',
    outputPath: 'processed/photo-no-bg.png'
);
```

### Using Queues (Recommended for Production)

[](#using-queues-recommended-for-production)

```
use ArtisanBuild\BackgroundRemover\Jobs\RemoveBackgroundJob;

// Dispatch to queue
RemoveBackgroundJob::dispatch(
    inputDisk: 's3',
    inputPath: 'uploads/photo.jpg',
    outputDisk: 's3',
    outputPath: 'processed/photo-no-bg.png'
);

// Dispatch to specific queue
RemoveBackgroundJob::dispatch(...)
    ->onQueue('image-processing');

// Dispatch to specific connection
RemoveBackgroundJob::dispatch(...)
    ->onConnection('redis');
```

Configuration
-------------

[](#configuration)

Publish the config file:

```
php artisan vendor:publish --tag=background-remover-config
```

This creates `config/background-remover.php`:

```
return [
    // Path to the binary (auto-installed to base_path('bin/bg-remover'))
    'binary_path' => env('BG_REMOVER_BINARY_PATH', base_path('bin/bg-remover')),

    // GitHub release settings
    'github' => [
        'repo' => 'artisan-build/bg-remover',
        'version' => 'latest', // or specific version like 'v1.0.0'
    ],

    // Platform (null = auto-detect)
    'platform' => env('BG_REMOVER_PLATFORM', null),

    // Timeout in seconds
    'timeout' => env('BG_REMOVER_TIMEOUT', 60),

    // Temporary directory for processing
    'temp_dir' => env('BG_REMOVER_TEMP_DIR', sys_get_temp_dir()),

    // Queue configuration
    'queue' => [
        'connection' => env('BG_REMOVER_QUEUE_CONNECTION', null),
        'queue' => env('BG_REMOVER_QUEUE', 'default'),
    ],
];
```

### Environment Variables

[](#environment-variables)

```
# Custom binary path
BG_REMOVER_BINARY_PATH=/usr/local/bin/bg-remover

# Force specific platform
BG_REMOVER_PLATFORM=alpine

# Timeout (seconds)
BG_REMOVER_TIMEOUT=120

# Queue settings
BG_REMOVER_QUEUE_CONNECTION=redis
BG_REMOVER_QUEUE=image-processing
```

Laravel Vapor Deployment
------------------------

[](#laravel-vapor-deployment)

The binary is automatically downloaded during build. No additional configuration needed!

```
# Vapor will automatically run:
php artisan background-removal:install
```

The Ubuntu binary works on AWS Lambda environments (including Vapor) and includes full ML support.

Laravel Forge Deployment
------------------------

[](#laravel-forge-deployment)

Add to your deployment script:

```
php artisan background-removal:install
```

The binary is installed to `base_path('bin/bg-remover')` and committed (or installed on each deploy).

Production Best Practices
-------------------------

[](#production-best-practices)

### 1. Use Queues

[](#1-use-queues)

Always process images asynchronously in production:

```
RemoveBackgroundJob::dispatch(...)
    ->onQueue('image-processing');
```

### 2. Configure Timeout

[](#2-configure-timeout)

For large images, increase the timeout:

```
BG_REMOVER_TIMEOUT=120
```

### 3. Monitor Storage

[](#3-monitor-storage)

The service downloads files to temporary storage for processing. Ensure adequate disk space:

```
// Default uses sys_get_temp_dir()
// Or customize:
BG_REMOVER_TEMP_DIR=/path/to/large/temp/dir
```

### 4. Error Handling

[](#4-error-handling)

Wrap processing in try-catch:

```
use Illuminate\Process\Exceptions\ProcessFailedException;

try {
    $service->removeBackgroundFromStorage(...);
} catch (ProcessFailedException $e) {
    Log::error('Background removal failed', [
        'error' => $e->getMessage(),
        'input' => $inputPath,
    ]);
}
```

Testing
-------

[](#testing)

```
# Run package tests
composer test

# Run with coverage
composer test:coverage
```

How It Works
------------

[](#how-it-works)

1. **Download**: Images are downloaded from Laravel Storage to temporary files
2. **Process**: The C++ binary processes the image using OpenCV's GrabCut algorithm
3. **Upload**: Processed images are uploaded back to Laravel Storage
4. **Cleanup**: Temporary files are automatically deleted

Platform Notes
--------------

[](#platform-notes)

### Ubuntu (Laravel Forge, Vapor, etc.)

[](#ubuntu-laravel-forge-vapor-etc)

- Uses system OpenCV libraries
- Includes ONNX Runtime for ML support
- Standard glibc-based binary
- ~23KB binary size

### macOS ARM64 (Development)

[](#macos-arm64-development)

- Native Apple Silicon binary
- Uses Homebrew OpenCV and ONNX Runtime
- Full ML support included
- Universal x86\_64 support coming soon

ML Mode
-------

[](#ml-mode)

All binaries are compiled with ML support via ONNX Runtime. To use ML-based segmentation:

```
# Download an ONNX model (e.g., U2-Net, RMBG-1.4)
# Then use with --ml flag
bg-remover -i input.jpg -o output.png --ml --model path/to/model.onnx
```

ML mode provides superior edge detection and works better with complex backgrounds compared to the traditional GrabCut algorithm.

Project Structure
-----------------

[](#project-structure)

```
background-remover/
├── src/                      # Laravel package source
│   ├── Commands/             # Artisan commands
│   ├── Jobs/                 # Queue jobs
│   ├── Providers/            # Service providers
│   └── Services/             # Background removal service
├── cpp-src/                  # C++ source code
│   ├── bg-remover.cpp        # Main C++ implementation
│   ├── Makefile              # Build system with ML support
│   ├── Dockerfile.ubuntu     # Ubuntu build with ONNX Runtime
│   └── README.md             # Build documentation
├── demo/                     # Interactive demo UI
│   ├── index.html            # Web interface
│   ├── process.php           # Processing endpoint
│   └── README.md             # Demo documentation
├── config/                   # Laravel config
├── tests/                    # Package tests
├── bin/                      # Binary installation directory
├── install-binary.sh         # Binary installation script
└── README.md                 # This file

```

Troubleshooting
---------------

[](#troubleshooting)

### Binary Not Found

[](#binary-not-found)

```
# For Laravel projects
php artisan background-removal:install

# For standalone usage
./install-binary.sh

# Or build from source
cd cpp-src && make && mkdir -p ../bin && cp bg-remover ../bin/
```

### Permission Denied

[](#permission-denied)

```
# Make binary executable
chmod +x bin/bg-remover
```

### Platform Not Supported

[](#platform-not-supported)

Build from source using the included C++ code:

```
cd cpp-src
# Follow instructions in cpp-src/README.md
```

Or see [FORKING.md](https://github.com/artisan-build/bg-remover/blob/main/FORKING.md) for building custom platform binaries.

Credits
-------

[](#credits)

- **Binary**: [artisan-build/bg-remover](https://github.com/artisan-build/bg-remover)
- **Algorithm**: OpenCV GrabCut
- **Maintained by**: [Artisan Build](https://artisan.build)

License
-------

[](#license)

MIT License. See [LICENSE.md](LICENSE.md) for details.

Related Projects
----------------

[](#related-projects)

- [artisan-build/bg-remover](https://github.com/artisan-build/bg-remover) - The C++ binary
- [artisan-build/scalpels](https://github.com/artisan-build/scalpels) - Collection of Laravel utilities

###  Health Score

19

—

LowBetter than 10% of packages

Maintenance56

Moderate activity, may be stable

Popularity0

Limited adoption so far

Community6

Small or concentrated contributor base

Maturity12

Early-stage or recently created project

 Bus Factor1

Top contributor holds 100% of commits — single point of failure

How is this calculated?**Maintenance (25%)** — Last commit recency, latest release date, and issue-to-star ratio. Uses a 2-year decay window.

**Popularity (30%)** — Total and monthly downloads, GitHub stars, and forks. Logarithmic scaling prevents top-heavy scores.

**Community (15%)** — Contributors, dependents, forks, watchers, and maintainers. Measures real ecosystem engagement.

**Maturity (30%)** — Project age, version count, PHP version support, and release stability.

### Community

Maintainers

![](https://www.gravatar.com/avatar/55eed7400c452edf7e7adfa4f1c6676b65b5ce1867fff6bddcb80b1bb45360af?d=identicon)[edgrosvenor](/maintainers/edgrosvenor)

---

Top Contributors

[![edgrosvenor](https://avatars.githubusercontent.com/u/1053395?v=4)](https://github.com/edgrosvenor "edgrosvenor (3 commits)")

### Embed Badge

![Health badge](/badges/artisan-build-background-remover/health.svg)

```
[![Health](https://phpackages.com/badges/artisan-build-background-remover/health.svg)](https://phpackages.com/packages/artisan-build-background-remover)
```

###  Alternatives

[milon/barcode

Barcode generator like Qr Code, PDF417, C39, C39+, C39E, C39E+, C93, S25, S25+, I25, I25+, C128, C128A, C128B, C128C, 2-Digits UPC-Based Extention, 5-Digits UPC-Based Extention, EAN 8, EAN 13, UPC-A, UPC-E, MSI (Variation of Plessey code)

1.5k13.3M39](/packages/milon-barcode)[bkwld/croppa

Image thumbnail creation through specially formatted URLs for Laravel

510496.0k22](/packages/bkwld-croppa)[char0n/ffmpeg-php

PHP wrapper for FFmpeg application

495225.1k1](/packages/char0n-ffmpeg-php)[goat1000/svggraph

Generates SVG graphs

132849.6k3](/packages/goat1000-svggraph)[cohensive/embed

Media Embed (for Laravel or as a standalone).

120370.4k](/packages/cohensive-embed)[netresearch/rte-ckeditor-image

Image support in CKEditor for the TYPO3 ecosystem - by Netresearch

63991.3k4](/packages/netresearch-rte-ckeditor-image)

PHPackages © 2026

[Directory](/)[Categories](/categories)[Trending](/trending)[Changelog](/changelog)[Analyze](/analyze)
