codebuds/webp-converter
Lightweight PHP 7.4+ WebP converter for Symfony apps. Convert JPEG/PNG/GIF/BMP to WebP from a file path or Symfony File, with options like quality, saveFile, force, output naming/path, and clear exceptions for invalid types or options.
Installation:
composer require codebuds/webp-converter
Basic Usage:
use CodeBuds\WebPConverter\WebPConverter;
$webpData = WebPConverter::createWebpImage('/path/to/image.jpg');
resource: GD image resource (if conversion succeeds).path: Expected file path for the converted WebP (if saveFile: true).First Use Case: Convert an uploaded image to WebP and save it:
$uploadedFile = $request->file('image');
$webpData = WebPConverter::createWebPImage($uploadedFile->getPathname(), [
'saveFile' => true,
'savePath' => storage_path('app/public/webp'),
'quality' => 75
]);
Batch Conversion (e.g., during asset optimization):
$images = glob(storage_path('app/public/uploads/*.{jpg,jpeg,png,gif}'));
foreach ($images as $image) {
try {
WebPConverter::createWebPImage($image, [
'saveFile' => true,
'savePath' => storage_path('app/public/webp'),
'force' => true // Overwrite existing files
]);
} catch (\Exception $e) {
Log::error("Failed to convert {$image}: " . $e->getMessage());
}
}
Dynamic Filename Handling:
Use filename and filenameSuffix to customize output:
$webpData = WebPConverter::createWebPImage('/path/to/image.jpg', [
'saveFile' => true,
'filename' => 'optimized_',
'filenameSuffix' => '_webp',
'savePath' => storage_path('app/public/webp')
]);
// Output: /storage/app/public/webp/optimized_image_webp.webp
Integration with Laravel Storage: Combine with Laravel’s filesystem for cloud storage (e.g., S3):
use Illuminate\Support\Facades\Storage;
$webpData = WebPConverter::createWebPImage($localPath, [
'saveFile' => false // Don’t save locally
]);
Storage::disk('s3')->put('webp/' . basename($localPath) . '.webp', file_get_contents($webpData['resource']));
Middleware for Automatic Conversion: Attach to file uploads in a middleware:
public function handle($request, Closure $next) {
if ($request->hasFile('image')) {
$file = $request->file('image');
$webpData = WebPConverter::createWebPImage($file->getPathname(), [
'saveFile' => true,
'savePath' => $file->getPath() . '/webp'
]);
$request->merge(['webp_path' => $webpData['path']]);
}
return $next($request);
}
Queue Background Jobs:
Offload conversions to a queue (e.g., convert-to-webp job):
ConvertToWebPJob::dispatch($imagePath, [
'savePath' => storage_path('app/public/webp'),
'quality' => 85
]);
Storage::disk()->put() to save the GD resource directly to cloud storage after conversion.intervention/image for resizing before conversion:
$img = Image::make($path)->resize(800, 600);
$img->save();
WebPConverter::createWebPImage($img->path(), ['quality' => 90]);
$cacheKey = md5($originalPath);
if (!Cache::has($cacheKey)) {
$webpData = WebPConverter::createWebPImage($originalPath, ['saveFile' => true]);
Cache::put($cacheKey, $webpData['path'], now()->addYears(1));
}
GD Extension Requirement:
Call to undefined function imagecreatefromjpeg().php-gd is installed and enabled in php.ini:
extension=gd
php -m | grep gd to verify.File Extension Mismatch:
.jpg files with incorrect MIME type.File::guessExtension() or validate MIME types before conversion:
$file = new \Symfony\Component\HttpFoundation\File\File($path);
if (!in_array(strtolower($file->guessExtension()), ['jpg', 'jpeg', 'png', 'gif', 'bmp'])) {
throw new \InvalidArgumentException('Unsupported file type');
}
Path Permissions:
Failed to open stream: Permission denied when saveFile: true.savePath directory is writable:
chmod -R 755 storage/app/public/webp
Quality Range:
Argument 3 passed to imagewebp() must be an integer between 0 and 100.quality option (default: 80):
$quality = max(0, min(100, ($options['quality'] ?? 80)));
Existing Files:
saveFile: true and file exists (unless force: true).'force' => true to overwrite or handle conflicts manually.Memory Limits:
Allowed memory size exhausted for large images.memory_limit in php.ini or optimize images before conversion.Log Exceptions:
Wrap conversions in try-catch blocks to log errors:
try {
$webpData = WebPConverter::createWebPImage($path, $options);
} catch (\Exception $e) {
Log::error("WebP Conversion Failed: " . $e->getMessage());
// Fallback to original format
}
Verify GD Support: Check supported formats with:
var_dump(gd_info()['GD Version'] ?? 'GD not installed');
Test with Known Files:
Use a small test image (e.g., test.jpg) to verify the package works before deploying:
$testPath = public_path('test.jpg');
file_put_contents($testPath, file_get_contents('https://via.placeholder.com/100'));
$result = WebPConverter::createWebPImage($testPath, ['saveFile' => true]);
Custom Filename Logic: Override default filename behavior by extending the class:
class CustomWebPConverter extends WebPConverter {
protected function generateFilename($originalPath, $options) {
$name = pathinfo($originalPath, PATHINFO_FILENAME);
return "custom_{$name}_" . time();
}
}
Post-Conversion Hooks: Add callbacks after conversion:
$webpData = WebPConverter::createWebPImage($path, [
'saveFile' => true,
'postConvert' => function($path) {
// Example: Generate a thumbnail or update a database record
ThumbnailGenerator::create($path);
}
]);
Fallback for Unsupported Formats:
Extend to support additional formats (e.g., SVG) by modifying the guessExtension logic:
protected function isSupported($extension) {
return in_array(strtolower($extension), ['jpg', 'jpeg', 'png', 'gif', 'bmp', 'svg']);
}
Progressive WebP:
Use GD’s imagewebp flags for progressive WebP:
$options = ['saveFile' => true, 'quality' => 80, 'flags' => IMG_WEBP_PROGRESSIVE];
$webpData = WebPConverter::createWebPImage($path, $options);
How can I help you explore Laravel packages today?