Weave Code
Code Weaver
Helps Laravel developers discover, compare, and choose open-source packages. See popularity, security, maintainers, and scores at a glance to make better decisions.
Feedback
Share your thoughts, report bugs, or suggest improvements.
Subject
Message

Webp Converter Laravel Package

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.

View on GitHub
Deep Wiki
Context7

Getting Started

Minimal Setup

  1. Installation:

    composer require codebuds/webp-converter
    
  2. Basic Usage:

    use CodeBuds\WebPConverter\WebPConverter;
    
    $webpData = WebPConverter::createWebpImage('/path/to/image.jpg');
    
    • Returns an array with:
      • resource: GD image resource (if conversion succeeds).
      • path: Expected file path for the converted WebP (if saveFile: true).
  3. 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
    ]);
    

Implementation Patterns

Core Workflows

  1. 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());
        }
    }
    
  2. 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
    
  3. 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']));
    
  4. 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);
    }
    
  5. 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
    ]);
    

Integration Tips

  • Laravel Filesystem: Use Storage::disk()->put() to save the GD resource directly to cloud storage after conversion.
  • Image Optimization: Chain with packages like intervention/image for resizing before conversion:
    $img = Image::make($path)->resize(800, 600);
    $img->save();
    WebPConverter::createWebPImage($img->path(), ['quality' => 90]);
    
  • Caching: Cache converted WebP files by filename to avoid reprocessing:
    $cacheKey = md5($originalPath);
    if (!Cache::has($cacheKey)) {
        $webpData = WebPConverter::createWebPImage($originalPath, ['saveFile' => true]);
        Cache::put($cacheKey, $webpData['path'], now()->addYears(1));
    }
    

Gotchas and Tips

Pitfalls

  1. GD Extension Requirement:

    • Error: Call to undefined function imagecreatefromjpeg().
    • Fix: Ensure php-gd is installed and enabled in php.ini:
      extension=gd
      
    • Check: Run php -m | grep gd to verify.
  2. File Extension Mismatch:

    • Error: Throws exception for .jpg files with incorrect MIME type.
    • Fix: Use 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');
      }
      
  3. Path Permissions:

    • Error: Failed to open stream: Permission denied when saveFile: true.
    • Fix: Ensure the savePath directory is writable:
      chmod -R 755 storage/app/public/webp
      
  4. Quality Range:

    • Error: Argument 3 passed to imagewebp() must be an integer between 0 and 100.
    • Fix: Validate quality option (default: 80):
      $quality = max(0, min(100, ($options['quality'] ?? 80)));
      
  5. Existing Files:

    • Error: Throws exception if saveFile: true and file exists (unless force: true).
    • Fix: Set 'force' => true to overwrite or handle conflicts manually.
  6. Memory Limits:

    • Error: Allowed memory size exhausted for large images.
    • Fix: Increase memory_limit in php.ini or optimize images before conversion.

Debugging Tips

  1. 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
    }
    
  2. Verify GD Support: Check supported formats with:

    var_dump(gd_info()['GD Version'] ?? 'GD not installed');
    
  3. 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]);
    

Extension Points

  1. 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();
        }
    }
    
  2. 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);
        }
    ]);
    
  3. 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']);
    }
    
  4. Progressive WebP: Use GD’s imagewebp flags for progressive WebP:

    $options = ['saveFile' => true, 'quality' => 80, 'flags' => IMG_WEBP_PROGRESSIVE];
    $webpData = WebPConverter::createWebPImage($path, $options);
    
Weaver

How can I help you explore Laravel packages today?

Conversation history is not saved when not logged in.
Prompt
Add packages to context
No packages found.
besmartand-pro/php-quality-config
sentix/ai-chatbot
codifyo/ts-generator-bundle
mintobit/jobqueue
a4sex/maintenance-bundle
a4sex/entity-date-update
a4sex/client-identifier
a4sex/base-utilites
a4sex/key-value-storage
a4sex/micro-status
chilldev/dependency-injection-extra
datinglibre/datinglibre-app-api
biberltd/corebundle
bricre/symfony-bundle-test
biberltd/logbundle
dominium/http-adapter-bundle
dominium/google-analytics
a4sex/auto-clean-entity
christhompsontldr/laravel-inky
spatie/mailcoach-vapor