PHP code example of marceli-to / image-cache

1. Go to this page and download the library: Download marceli-to/image-cache 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/ */

    

marceli-to / image-cache example snippets


// config/filesystems.php
'disks' => [
    // ...
    'public' => [
        'driver' => 'local',
        'root' => storage_path('app/public'),
        'url' => env('APP_URL').'/storage',
        'visibility' => 'public',
    ],
    // ...
],

// config/app.php
'providers' => [
    // ...
    MarceliTo\ImageCache\ImageCacheServiceProvider::class,
],

'aliases' => [
    // ...
    'ImageCache' => MarceliTo\ImageCache\Facades\ImageCache::class,
],

use MarceliTo\ImageCache\Facades\ImageCache;

// Get a cached image
$path = ImageCache::getCachedImage('large', 'image.jpg');

// Display the image in a view
<img src="{{ asset('storage/cache/images/' . basename($path)) }}" alt="Image">

use MarceliTo\ImageCache\Facades\ImageCache;

class ImageController extends Controller
{
    public function show($template, $filename)
    {
        try {
            $path = ImageCache::getCachedImage($template, $filename);
            
            if (!$path) {
                return response()->make('Image not found', 404);
            }
            
            return response()->file($path);
        } catch (InvalidArgumentException $e) {
            // Handle validation errors
            return response()->make('Invalid input: ' . $e->getMessage(), 400);
        } catch (Exception $e) {
            // Handle unexpected errors
            Log::error("Error in image controller: {$e->getMessage()}", [
                'exception' => $e
            ]);
            return response()->make('Server error', 500);
        }
    }
}

// config/image-cache.php
'register_routes' => false,

// routes/web.php
Route::get('/img/{template}/{filename}/{maxW?}/{maxH?}/{coords?}', [ImageController::class, 'getResponse']);

// App\Http\Controllers\ImageController.php
public function getResponse(Request $request, string $template, string $filename, ?string $maxW = null, ?string $maxH = null, ?string $coords = null): Response
{
    try {
        // Validate inputs
        $this->validateTemplate($template);
        $this->validateFilename($filename);
        
        $params = [];
        
        if ($maxW) {
            $this->validateMaxDimension($maxW, 'maxWidth');
            $params['maxWidth'] = (int) $maxW;
        }
        
        if ($maxH) {
            $this->validateMaxDimension($maxH, 'maxHeight');
            $params['maxHeight'] = (int) $maxH;
        }
        
        if ($coords) {
            $this->validateCoords($coords);
            $params['coords'] = $coords;
        }
        
        $path = ImageCache::getCachedImage($template, $filename, $params);
        
        if (!$path) {
            return response()->make('Image not found', 404);
        }
        
        return response()->file($path);
    } catch (Exception $e) {
        // Handle errors
        return response()->make('Error: ' . $e->getMessage(), 400);
    }
}

use MarceliTo\ImageCache\Facades\ImageCache;
use InvalidArgumentException;
use RuntimeException;

try {
    // Get a cached image
    $path = ImageCache::getCachedImage('large', 'image.jpg', [
        'maxWidth' => 1200,
        'maxHeight' => 800
    ]);

    // Get a cached image with cropping
    $path = ImageCache::getCachedImage('crop', 'image.jpg', [
        'maxWidth' => 800,
        'maxHeight' => 600,
        'coords' => '200,300,100,150',  // Format: width,height,x,y
        'ratio' => '16x9'
    ]);
    
    if (!$path) {
        // Handle image not found
    }
} catch (InvalidArgumentException $e) {
    // Handle validation errors
    Log::warning("Invalid input: {$e->getMessage()}");
} catch (RuntimeException $e) {
    // Handle runtime errors
    Log::error("Error processing image: {$e->getMessage()}");
} catch (Exception $e) {
    // Handle unexpected errors
    Log::error("Unexpected error: {$e->getMessage()}");
}

use MarceliTo\ImageCache\Facades\ImageCache;

try {
    // Clear all cached images
    $success = ImageCache::clearAllCache();

    // Clear cached images for a specific template
    $success = ImageCache::clearTemplateCache('large');
    
    // Clear cached images for a specific file
    $success = ImageCache::clearImageCache('image.jpg');
} catch (Exception $e) {
    Log::error("Error clearing cache: {$e->getMessage()}");
}



namespace App\ImageTemplates;

use Intervention\Image\Interfaces\ImageInterface;
use Intervention\Image\Interfaces\ModifierInterface;

class CustomTemplate implements ModifierInterface
{
    /**
     * Maximum width for the image
     */
    protected int $maxWidth = 1000;
    
    /**
     * Maximum height for the image
     */
    protected int $maxHeight = 800;
    
    /**
     * Apply filter to image
     */
    public function apply(ImageInterface $image): ImageInterface
    {
        // Get image orientation
        $orientation = $image->height() > $image->width() ? 'portrait' : 'landscape';
        
        // Scale down the image based on orientation while maintaining aspect ratio
        if ($orientation === 'landscape') {
            return $image->scaleDown(width: $this->maxWidth);
        } else {
            return $image->scaleDown(height: $this->maxHeight);
        }
    }
}

// config/image-cache.php
'templates' => [
    'custom' => \App\ImageTemplates\CustomTemplate::class,
    // ...other templates
],
bash
php artisan vendor:publish --tag=image-cache-config
bash
php artisan storage:link
bash
php artisan vendor:publish --tag=image-cache-config