PHP code example of onlinedigital / laravel-perfect-image

1. Go to this page and download the library: Download onlinedigital/laravel-perfect-image library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

onlinedigital / laravel-perfect-image example snippets


use Illuminate\Foundation\Configuration\Middleware;

return Application::configure(basePath: dirname(__DIR__))
    ->withMiddleware(function (Middleware $middleware) {
        $middleware->alias([
            'perfect-image' => \OnlineDigital\PerfectImage\Http\Middleware\InjectPerfectImageJs::class,
        ]);
    })
    ->create();

Route::get('/home', [HomeController::class, 'index'])->middleware('perfect-image');

// config/perfect-image.php
return [
    // Cache driver to store resolution data
    'cache_driver' => env('PERFECT_IMAGE_CACHE_DRIVER', 'file'),
    
    // Enable the collection of rendered image dimensions (tracking attributes,
    // JS injection and the observer endpoint). When disabled, the endpoint
    // answers with HTTP 403 {"code": "collect_dimensions_disabled"}.
    'collect_dimensions' => env('PERFECT_IMAGE_COLLECT_DIMENSIONS', false),

    // How many of the most common resolutions to keep
    'max_resolutions' => 5,
    
    // Minimum width difference to count as a new resolution
    'min_width_diff' => 50,
    
    // The route name for the observer endpoint
    'route_name' => '_perfect_image_observer',
    
    // Default image driver (url, cloudinary, etc.)
    'driver' => env('PERFECT_IMAGE_DRIVER', 'url'),
    
    // Driver-specific configuration
    'drivers' => [
        'url' => [
            // For simple URL manipulation (e.g., adding query params)
            'base_url' => env('APP_URL'),
            'param_format' => '{url}?w={width}&h={height}', // or {url}/{width}x{height}
        ],
        'cloudinary' => [
            'cloud_name' => env('CLOUDINARY_CLOUD_NAME'),
            'base_url' => 'https://res.cloudinary.com/{cloud_name}/image/upload',
        ],
        // Add more drivers as needed
    ],
];



namespace App\Drivers;

use OnlineDigital\PerfectImage\Contracts\Driver;

class MyCustomDriver implements Driver
{
    public function generateUrl(string $url, int $width, ?int $height = null): string
    {
        // Generate the URL for the resized image
        return "https://my-cdn.com/{$width}x{$height}/{$url}";
    }
}

$this->app->bind(\OnlineDigital\PerfectImage\Contracts\Driver::class, MyCustomDriver::class);
bash
php artisan vendor:publish --provider="OnlineDigital\\PerfectImage\\PerfectImageServiceProvider" --tag="perfect-image-config"