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/ */
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;
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);
}
}
}