PHPackages                             justsmiletoo/laravel-file-compressor - 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. [File &amp; Storage](/categories/file-storage)
4. /
5. justsmiletoo/laravel-file-compressor

ActiveLibrary[File &amp; Storage](/categories/file-storage)

justsmiletoo/laravel-file-compressor
====================================

Automatically compress images, PDFs and videos on upload in Laravel. Auto-detects MIME type and applies the right compressor with zero configuration.

v1.4.0(1mo ago)0659↑220%MITPHPPHP ^8.2CI passing

Since Mar 24Pushed 1mo agoCompare

[ Source](https://github.com/justsmiletoo/laravel-file-compressor)[ Packagist](https://packagist.org/packages/justsmiletoo/laravel-file-compressor)[ RSS](/packages/justsmiletoo-laravel-file-compressor/feed)WikiDiscussions master Synced 3w ago

READMEChangelog (4)Dependencies (14)Versions (7)Used By (0)

Laravel File Compressor
=======================

[](#laravel-file-compressor)

[![CI](https://github.com/justsmiletoo/laravel-file-compressor/actions/workflows/ci.yml/badge.svg)](https://github.com/justsmiletoo/laravel-file-compressor/actions/workflows/ci.yml)[![Latest Version on Packagist](https://camo.githubusercontent.com/3fae0891133e9aa7987ebe4eab9ba6207c624a268c2eed811397d47374ff831a/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f762f6a757374736d696c65746f6f2f6c61726176656c2d66696c652d636f6d70726573736f722e737667)](https://packagist.org/packages/justsmiletoo/laravel-file-compressor)[![Total Downloads](https://camo.githubusercontent.com/9944d7c33b9b5d8fb8006345edb2ff2c4e6a330e999e67d51512aec0fca6cd88/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f64742f6a757374736d696c65746f6f2f6c61726176656c2d66696c652d636f6d70726573736f722e737667)](https://packagist.org/packages/justsmiletoo/laravel-file-compressor)[![License](https://camo.githubusercontent.com/fc0a35afb589dc999964df220bc20aef1e46cc6f1ce58a7ddeb335eadd2d2ab7/68747470733a2f2f696d672e736869656c64732e696f2f7061636b61676973742f6c2f6a757374736d696c65746f6f2f6c61726176656c2d66696c652d636f6d70726573736f722e737667)](https://packagist.org/packages/justsmiletoo/laravel-file-compressor)

Automatically compress images, PDFs and videos on upload in Laravel. Auto-detects the MIME type and applies the right compressor — zero config needed.

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

[](#requirements)

- PHP 8.2+
- Laravel 11 or 12
- GD extension (default) or Imagick
- **Optional:** Ghostscript (`gs`) for PDF compression
- **Optional:** FFmpeg (`ffmpeg`) for video compression

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

[](#installation)

```
composer require justsmiletoo/laravel-file-compressor
```

The service provider is auto-discovered. To publish the config file:

```
php artisan vendor:publish --tag=file-compressor-config
```

### System binaries (optional)

[](#system-binaries-optional)

For PDF compression, install Ghostscript:

```
# Alpine (Docker)
apk add ghostscript

# Ubuntu/Debian
apt-get install ghostscript

# macOS
brew install ghostscript
```

For video compression, install FFmpeg:

```
# Alpine (Docker)
apk add ffmpeg

# Ubuntu/Debian
apt-get install ffmpeg

# macOS
brew install ffmpeg
```

Usage
-----

[](#usage)

### Auto-detect and compress

[](#auto-detect-and-compress)

The `compress()` method detects the file type and delegates to the right compressor:

```
use JustSmileToo\FileCompressor\FileCompressor;

// From an UploadedFile (typical controller usage)
$result = app(FileCompressor::class)->compress($request->file('avatar'));

// From a file path
$result = app(FileCompressor::class)->compress('/path/to/file.jpg');

// Using the facade
use JustSmileToo\FileCompressor\Facades\FileCompressor;

$result = FileCompressor::compress($uploadedFile);
```

### Type-specific methods

[](#type-specific-methods)

Skip MIME detection and call a compressor directly:

```
$result = FileCompressor::compressImage($file);
$result = FileCompressor::compressPdf($file);
$result = FileCompressor::compressVideo($file);
```

### Presets

[](#presets)

Use named presets for common image use cases:

```
// Uses the 'avatar' preset: 200x200, cover mode, quality 80
$result = FileCompressor::compressImage($file, ['preset' => 'avatar']);

// Uses 'banner' preset: 1920xAuto, scale mode, quality 85
$result = FileCompressor::compressImage($file, ['preset' => 'banner']);

// Override a preset value
$result = FileCompressor::compressImage($file, [
    'preset' => 'avatar',
    'max_width' => 300,
    'max_height' => 300,
]);
```

Define your own presets in the config:

```
// config/file-compressor.php
'image' => [
    'presets' => [
        'avatar' => ['max_width' => 200, 'max_height' => 200, 'mode' => 'cover', 'quality' => 80],
        'thumbnail' => ['max_width' => 300, 'max_height' => 300, 'mode' => 'cover', 'quality' => 80],
        'banner' => ['max_width' => 1920, 'max_height' => 600, 'mode' => 'scale', 'quality' => 85],
        'receipt' => ['max_width' => 1200, 'mode' => 'scale', 'quality' => 80, 'convert_to' => 'webp'],
    ],
],
```

### Resize modes

[](#resize-modes)

- **`scale`** (default) — Proportionally scale down. Never upscales. Aspect ratio preserved.
- **`cover`** — Crop and resize to fill exact dimensions (like CSS `object-fit: cover`).

```
// Scale down proportionally
$result = FileCompressor::compressImage($file, ['mode' => 'scale']);

// Crop to exact 200x200
$result = FileCompressor::compressImage($file, [
    'max_width' => 200,
    'max_height' => 200,
    'mode' => 'cover',
]);
```

### Per-call options

[](#per-call-options)

Override config values for a single call:

```
// Smaller avatar with WebP conversion
$result = FileCompressor::compressImage($file, [
    'max_width' => 400,
    'max_height' => 400,
    'quality' => 70,
    'convert_to' => 'webp',
]);

// High-quality PDF
$result = FileCompressor::compressPdf($file, [
    'quality' => 'printer', // screen, ebook, printer, prepress
]);

// Lower quality video for previews
$result = FileCompressor::compressVideo($file, [
    'crf' => 32,
    'max_width' => 720,
    'preset' => 'fast',
]);
```

### CompressionResult

[](#compressionresult)

Every compression call returns a `CompressionResult` DTO:

```
$result = FileCompressor::compress($file);

$result->path;              // string — path to the compressed file
$result->originalSize;      // int — original file size in bytes
$result->compressedSize;    // int — compressed file size in bytes
$result->mimeType;          // string — MIME type of the output
$result->wasCompressed;     // bool — false if compression was skipped or didn't reduce size
$result->savedBytes();      // int — bytes saved
$result->savedPercentage(); // float — e.g. 65.42
```

### Integration example

[](#integration-example)

Typical usage in a file upload service:

```
use Illuminate\Http\UploadedFile;
use Illuminate\Support\Facades\Storage;
use JustSmileToo\FileCompressor\FileCompressor;

class FileUploadService
{
    public function __construct(
        private FileCompressor $compressor,
    ) {}

    public function upload(UploadedFile $file, string $directory): string
    {
        $result = $this->compressor->compress($file);

        $filename = uniqid() . '.' . $file->getClientOriginalExtension();

        if ($result->wasCompressed) {
            return Storage::disk('public')->putFileAs(
                $directory,
                new \Illuminate\Http\File($result->path),
                $filename,
            );
        }

        return $file->storeAs($directory, $filename, 'public');
    }
}
```

### Check support

[](#check-support)

```
FileCompressor::isSupported('image/jpeg'); // true
FileCompressor::isSupported('text/plain'); // false
FileCompressor::isEnabled();               // true (unless disabled in config)
```

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

[](#configuration)

KeyDefaultDescription`enabled``true`Global toggle. Set to `false` to skip all compression.`temp_dir``sys_get_temp_dir()`Temporary directory for processing.**Image**`image.driver``gd`Image driver: `gd` or `imagick`.`image.quality``80`JPEG/WebP quality (1-100).`image.max_width``1920`Max width in pixels. Aspect ratio preserved.`image.max_height``1080`Max height in pixels. Aspect ratio preserved.`image.mode``scale`Resize mode: `scale` (proportional) or `cover` (crop to fill).`image.convert_to``null`Convert format: `null` (keep original), `webp`, `jpg`, `png`.`image.presets``[...]`Named presets with per-preset options. See [Presets](#presets).**PDF**`pdf.binary``gs`Path to the Ghostscript binary.`pdf.quality``ebook`Preset: `screen` (72dpi), `ebook` (150dpi), `printer` (300dpi), `prepress`.`pdf.timeout``60`Process timeout in seconds.**Video**`video.binary``ffmpeg`Path to the FFmpeg binary.`video.codec``libx264`Video codec.`video.crf``28`Constant Rate Factor (0-51). Lower = better quality, larger file.`video.preset``medium`Encoding speed preset. Slower = better compression.`video.max_width``1280`Max width in pixels (never upscales).`video.audio_bitrate``128k`Audio bitrate.`video.timeout``300`Process timeout in seconds.All values can be overridden via environment variables. See `config/file-compressor.php` for the full list.

Handling unsupported files
--------------------------

[](#handling-unsupported-files)

If a file type is not supported, `compress()` throws `UnsupportedFileTypeException`. You can check support beforehand:

```
use JustSmileToo\FileCompressor\Exceptions\UnsupportedFileTypeException;

if (FileCompressor::isSupported($file->getMimeType())) {
    $result = FileCompressor::compress($file);
} else {
    // Store without compression
}
```

Or catch the exception:

```
try {
    $result = FileCompressor::compress($file);
} catch (UnsupportedFileTypeException) {
    // File type not supported, store as-is
}
```

Temp file cleanup
-----------------

[](#temp-file-cleanup)

Compressed files are written to the configured `temp_dir`. After storing the compressed file to your disk, the temp file can be safely deleted. The OS will also clean up temp files periodically.

Testing
-------

[](#testing)

```
composer test
```

Place test fixtures (`sample.jpg`, `sample.pdf`, `sample.mp4`) in `tests/Fixtures/` to enable all tests.

License
-------

[](#license)

MIT. See [LICENSE](LICENSE).

###  Health Score

45

—

FairBetter than 91% of packages

Maintenance92

Actively maintained with recent releases

Popularity17

Limited adoption so far

Community8

Small or concentrated contributor base

Maturity51

Maturing project, gaining track record

 Bus Factor1

Top contributor holds 69.2% 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.

###  Release Activity

Cadence

Every ~14 days

Total

5

Last Release

39d ago

### Community

Maintainers

![](https://avatars.githubusercontent.com/u/65900295?v=4)[Sidi jeddou](/maintainers/sididev)[@sidiDev](https://github.com/sidiDev)

---

Top Contributors

[![SIDIDEV1](https://avatars.githubusercontent.com/u/48436918?v=4)](https://github.com/SIDIDEV1 "SIDIDEV1 (9 commits)")[![github-actions[bot]](https://avatars.githubusercontent.com/in/15368?v=4)](https://github.com/github-actions[bot] "github-actions[bot] (4 commits)")

---

Tags

laravelpdfimagecompressionresizevideoffmpeguploadghostscriptoptimize

###  Code Quality

TestsPest

Static AnalysisPHPStan

Code StyleLaravel Pint

Type Coverage Yes

### Embed Badge

![Health badge](/badges/justsmiletoo-laravel-file-compressor/health.svg)

```
[![Health](https://phpackages.com/badges/justsmiletoo-laravel-file-compressor/health.svg)](https://phpackages.com/packages/justsmiletoo-laravel-file-compressor)
```

###  Alternatives

[unisharp/laravel-filemanager

A file upload/editor intended for use with Laravel 5 to 10 and CKEditor / TinyMCE

2.1k3.4M81](/packages/unisharp-laravel-filemanager)[psalm/plugin-laravel

Psalm plugin for Laravel

3345.1M337](/packages/psalm-plugin-laravel)[laravel/ai

The official AI SDK for Laravel.

9782.1M162](/packages/laravel-ai)[moonshine/moonshine

Laravel administration panel

1.3k239.9k76](/packages/moonshine-moonshine)[intervention/image-laravel

Laravel Integration of Intervention Image

1558.1M159](/packages/intervention-image-laravel)[mostafaznv/larupload

Larupload is a ORM based file uploader for laravel to upload image, video, audio and other known files.

75441.8k6](/packages/mostafaznv-larupload)

PHPackages © 2026

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