justsmiletoo/laravel-file-compressor
Composer 安装命令:
composer require 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.
README 文档
README
Automatically compress images, PDFs and videos on upload in Laravel. Auto-detects the MIME type and applies the right compressor — zero config needed.
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
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)
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
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
Skip MIME detection and call a compressor directly:
$result = FileCompressor::compressImage($file); $result = FileCompressor::compressPdf($file); $result = FileCompressor::compressVideo($file);
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
scale(default) — Proportionally scale down. Never upscales. Aspect ratio preserved.cover— Crop and resize to fill exact dimensions (like CSSobject-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
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
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
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
FileCompressor::isSupported('image/jpeg'); // true FileCompressor::isSupported('text/plain'); // false FileCompressor::isEnabled(); // true (unless disabled in config)
Configuration
| Key | Default | Description |
|---|---|---|
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. |
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
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
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
composer test
Place test fixtures (sample.jpg, sample.pdf, sample.mp4) in tests/Fixtures/ to enable all tests.
License
MIT. See LICENSE.
justsmiletoo/laravel-file-compressor 适用场景与选型建议
justsmiletoo/laravel-file-compressor 是一款 基于 PHP 开发的 Composer 扩展包,目前已累计 703 次下载、GitHub Stars 达 0, 最近一次更新时间为 2026 年 03 月 24 日, 在 PHP 生态内属于活跃度较高的组件。
它主要适用于以下技术方向: 「image」 「compression」 「upload」 「pdf」 「video」 「resize」 等业务场景。在实际项目中,围绕这些方向常见需要落地的问题包括:接口对接、性能调优、并发安全、与既有框架(Laravel / ThinkPHP / Yii / Webman 等)的兼容适配,以及生产环境的日志埋点与稳定性保障。
我们在过去多个企业项目中使用过 justsmiletoo/laravel-file-compressor 或与其功能相近的方案,如果你在选型或落地过程中遇到问题,例如 版本兼容、二次改造、私有化封装、与内部系统对接、生产 BUG 排查,欢迎联系我们协助评估。
基于 justsmiletoo/laravel-file-compressor 在你已有业务上做功能扩展、字段裁剪、UI 适配、与内部账号 / 权限 / 日志系统的深度对接。
线上偶发问题、内存泄漏、慢查询、并发异常等排查修复;针对高流量场景做缓存、队列、索引层面的调优。
承接完整的项目从需求 → 设计 → 开发 → 上线 → 长期运维;也可按月提供技术保姆服务。
与 justsmiletoo/laravel-file-compressor 相关的其它包
同方向 / 同关键字的高下载量 PHP Composer 包推荐,方便对比选型:
Asset Management for PHP
Image optimization / compression library. This library is able to optimize png, jpg and gif files in very easy and handy way. It uses optipng, pngquant, pngcrush, pngout, gifsicle, jpegoptim and jpegtran tools.
The file manager intended for using Laravel with CKEditor / TinyMCE / Colorbox
Yii2 LightBox image galary widget uses Lightbox v2.10.0 by Lokesh Dhakar
The Yii2 extension uses jQuery jquery.carousel-1.1.min.js and makes image carousel from php array of structure defined.
The Yii2 extension uses jQuery PrettyPhoto and OwlCarousel js and makes image galary from php array of structure defined.
统计信息
- 总下载量: 703
- 月度下载量: 0
- 日度下载量: 0
- 收藏数: 0
- 点击次数: 44
- 依赖项目数: 0
- 推荐数: 0
其他信息
- 授权协议: MIT
- 更新时间: 2026-03-24