Use Cloudinary and cache the images using it.
Caching Images in Redis?
Should I Cache .webp Images in Redis?
I’m working on a Laravel blog and wondering if caching .webp images in Redis is a good practice. Would this improve performance, or should I rely on browser caching instead?
and to use redis, here is a sample code
use Illuminate\Support\Facades\Cache;
use Illuminate\Support\Facades\Storage;
public function getImage($imageName)
{
// Define a unique cache key
$cacheKey = 'image_cache_' . $imageName;
// Try to retrieve the image from Redis cache
$cachedImage = Cache::get($cacheKey);
if ($cachedImage) {
// If image is in cache, return it
return response($cachedImage, 200, ['Content-Type' => 'image/jpeg']);
} else {
// If image is not in cache, retrieve from storage
$imagePath = Storage::path('images/' . $imageName);
if (!file_exists($imagePath)) {
abort(404, 'Image not found');
}
// Read the image from the file
$image = file_get_contents($imagePath);
// Cache the image in Redis (you can set an expiration time)
Cache::put($cacheKey, $image, 3600); // Cache for 1 hour
// Return the image response
return response($image, 200, ['Content-Type' => 'image/jpeg']);
}
}
I'd serve them normally or use a CDN.
I doubt reading images from a disk is a performance bottleneck in most applications. Operating systems already have an in-memory cache (page cache) for frequently accessed files.
While you technically could implement image caching via Redis, it would only help if you served the images in a way that allowed browsers to cache them. At best, you'd be replacing a single disk read with a Redis query per image per client. Compared to a CDN, you'd have to serve the images from a centralized location, and you'd be bloating your RAM usage.
But if you feel like experimenting, go ahead. Just remember: images have to be cacheable by the browser. Otherwise, you'd be constantly pulling large amounts of binary data from Redis and sending it over the network, which would be way worse than the default.
Please or to participate in this conversation.