Caching extension for the Intervention Image Class

Overview

Intervention Image Cache

Intervention Image Cache extends the Intervention Image Class package to be capable of image caching functionality.

The library uses the Illuminate/Cache package and can be easily integrated into the Laravel Framework. Based on your Laravel cache configuration you are able to choose between Filesystem, Database, Memcached or Redis for the temporary buffer store.

The principle is simple. Every method call to the Intervention Image class is captured and checked by the caching interface. If this particular sequence of operations already have taken place, the data will be loaded directly from the cache instead of a resource-intensive image operation.

Installation

You can install this package quickly and easily with Composer.

Require the package via Composer:

$ composer require intervention/imagecache

Now you are able to require the vendor/autoload.php file to PSR-4 autoload the library.

Laravel Integration

The Image Cache class supports Laravel integration. Best practice to use the library in Laravel is to add the ServiceProvider and Facade of the Intervention Image Class.

Open your Laravel config file config/app.php and add the following lines.

In the $providers array add the service providers for this package.

'providers' => array(

    [...]

    'Intervention\Image\ImageServiceProvider'
),

Add the facade of this package to the $aliases array.

'aliases' => array(

    [...]

    'Image' => 'Intervention\Image\Facades\Image'
),

Usage

The Image Cache is best called by the static method Image::cache from the Intervention Image class.

To create cached images just use the static method Image::cache and pass the image manipulations via closure. The method will automatically detect if a cached file for your particular operations exists.

// run the operations on the image or read a file
// for the particular operations from cache
$img = Image::cache(function($image) {
   return $image->make('public/foo.jpg')->resize(300, 200)->greyscale();
});

Determine a lifetime in minutes for the cache file as an optional second parameter. Pass a boolean true as optional third parameter to return an Intervention Image object instead of a image stream.

// determine a lifetime and return as object instead of string
$img = Image::cache(function($image) {
   return $image->make('public/foo.jpg')->resize(300, 200)->greyscale();
}, 10, true);

Server configuration

If you have Static Resources caching enabled on Nginx please add your cache directory ({route} in config) to static resources handler exclusion:

# where "cache" is {route}
location ~* ^\/(?!cache).*\.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc|webp|woff|woff2)$ {
  expires max;
  access_log off;
  add_header Cache-Control "public";
}

License

Intervention Imagecache Class is licensed under the MIT License.

Comments
  • What im doing wrong

    What im doing wrong

    url); Image::cache(function($image) use ($data) { return $image->make($data); }, 10); ?>
      <a class="cboxElement" href="{{ $movieDetails->url }}" title="{{$movieDetails->c00}}"><img class="thumbnail" src="{{ $data }}" alt="..."></a>
    

    im trying to cache a image from a url them i want to display it inside that image tag im having trouble i get just raw data on the browser like this..

    image

    opened by selif00 17
  • is_file() expects parameter 1 to be a valid path

    is_file() expects parameter 1 to be a valid path

    When upgrading to 2.0.5 an error is thrown:

    local.ERROR: exception 'ErrorException' with message 'is_file() expects parameter 1 to be a valid path, string given'...

    which means that file/line:

    intervention/imagecache/src/Intervention/Image/ImageCache.php(119)

    php -v PHP 5.6.2 (built: Nov 8 2014 20:00:07) Copyright (c) 1997-2014 The PHP Group Zend Engine v2.6.0, Copyright (c) 1998-2014 Zend Technologies

    opened by stevenklar 8
  • Composer Update Issue

    Composer Update Issue

    Hello, it seems that possible recent version number changes have caused a hiccup in installation through composer. Upon updating through composer I get the following.

    intervention/imagecache dev-master requires intervention/image 2.* -> no matching package found.
    
    opened by adamjacob 8
  • Sanity check...

    Sanity check...

    So sorry to feel the need to ask. I'm just struggling a bit with whether what I've done is a good way to implement image caching or not - and there doesn't seem to be a whole heap of examples around for how to utilise imagecache. Thank you for your excellent work BTW!

    /*
    |--------------------------------------------------------------------------
    | Imagecache Routes
    |--------------------------------------------------------------------------
    */
    Route::any('imagecache/{style}/{filepath}', array('as' => 'imagecache', function($style, $filepath)
    {
      // Get the full path to the image (locked to the 'public/assets' folder).
      $filepath = public_path() . "/assets/{$filepath}";
    
      // 404 if the image doesn't exist.
      if (!File::isFile($filepath))
      {
        App::abort(404, 'File not found');
      }
    
      // Produce the cached image.
      $image = Image::cache(function($image) use ($style, $filepath)
      {
        // Switch on the passed image style preset.
        switch ($style)
        {
          case 'square_thumbnail':
            return $image->make($filepath)->resize(100, 100, false)->greyscale();
          case 'thumbnail':
            return $image->make($filepath)->resize(100, 100, true)->greyscale();
          case 'medium':
            return $image->make($filepath)->resize(220, 220, true);
          case 'large':
            return $image->make($filepath)->resize(480, 480, true);
          case 'preview':
            return $image->make($filepath)->resize(640, null, true);
          // 404 if there's no such image style preset.
          default:
            App::abort(404, 'Image style not found');
        }
    
      }, 10, true);
    
      // Return an image response.
      return Response::make($image, 200, array('content-type' => 'image/jpg'));
    }))->where('filepath', '.*');
    

    My concerns are;

    • File security (I've seen that using /../../ doesn't work - thank you Laravel) but maybe I'm overlooking something?
    • DDOS - a' la http://berk.es/2013/03/04/drupal-imagecache-security-vulnarability-with-ddos-attack-explained/
    • The image object returned doesn't appear to contain a mimetype (it's NULL) so I've just hardcoded 'image/jpg' for the response but this isn't ideal

    Any advice or comments would be very much appreciated, thank you.

    opened by pobtastic 8
  • Laravel 4.2 URL manipulation not working

    Laravel 4.2 URL manipulation not working

    I found that ImageServiceProviderLaravel4 is not working properly, the commented out code shown below was preventing to get this functionality to work, I fixed it by using the same flow that the ImageCacheController is using:

    /*
                        if (is_callable($callback)) {
    
                            // image manipulation based on callback
                            $content = $app['image']->cache(function ($image) use ($image_path, $callback) {
                                return $callback($image->make($image_path));
                            }, $config->get('imagecache::lifetime'));
    
                        } else {
    
                            // get original image file contents
                            $content = file_get_contents($image_path);
                        }
    
                        // define mime type
                        $mime = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $content);
    
                        // return http response
                        return new IlluminateResponse($content, 200, array(
                            'Content-Type' => $mime,
                            'Cache-Control' => 'max-age='.($config->get('imagecache::lifetime')*60).', public',
                            'Etag' => md5($content)
                        ));
                        */
    
                        $manager = new ImageManager;
                        $content = $manager->cache(function ($image) use ($callback, $image_path) {
    
                            if ($callback instanceof Closure) {
                                // build from closure callback template
                                $callback($image->make($image_path));
                            } else {
                                // build from filter template
    
                                $filter = new $callback();
    
                                $image->make($image_path)->filter($filter);
                            }
    
                        }, $config->get('imagecache::lifetime'));
    
                        // define mime type
                        $mime = finfo_buffer(finfo_open(FILEINFO_MIME_TYPE), $content);
    
                        // return http response
                        return new IlluminateResponse($content, 200, array(
                            'Content-Type' => $mime,
                            'Cache-Control' => 'max-age='.($config->get('imagecache.lifetime')*60).', public',
                            'Etag' => md5($content)
                        ));
    
    
    opened by phyroslam 7
  • vendor:publish not showing any configs

    vendor:publish not showing any configs

    I am upgrading my system with a fresh start in Laravel 5. Imagecache for L4 came with a config file, so I am assuming L5 version has one as well. When I do a "php artisan vendor:publish" I am receiving a "Noting to publish" error. Am I missing something in the setup?

    opened by calebsmithdev 7
  • Remote storage paths

    Remote storage paths

    This is more of a feature request but would it be possible to add remote storage lookup such as Amazons's S3. Currently its only local paths:

        'paths' => array(
            public_path('upload'),
            public_path('images'),
        ),
    

    Would be cool to be able to find images in an S3 bucket and then create the cache version based on that.

    opened by atmediauk 7
  • Image cache returning corrupted image?

    Image cache returning corrupted image?

    Hi All,

    Yesterday I've updated to version 2.* and now I'm having a problem. The image is not created/showed properly (I just get a non image icon in the browser).

    I'm just doing:

    $img = Image::cache(function($image) { return $image->make($GLOBALS['file'])->widen(250); }); return Response::make($img, 200, array('Content-Type' => 'image/jpeg'));

    It use to work in version 1.*

    Cheers

    opened by rogerfn 7
  • Strange - getting 404 response even though image is returned

    Strange - getting 404 response even though image is returned

    I am getting a 404 response, see: https://athliit.com/images/cover_thumbnail/90271b285b66934460d8a5543fa5aceb.jpg

    Even though the images is loaded and returned. Why is this?

    opened by simplenotezy 6
  • i don't know

    i don't know

    2014-07-09 4 09 17

    my code in laravel is $url = 'https://s3-ap-northeast-1.amazonaws.com/tmp-photos/12c9f90f559f6ef65f3cfe5854c3574b/1404207756862.jpg';
    $cache_image = Image::cache(function($img) use ($url) { return Image::make($url)->resize(200,200)->greyscale(); },10,true); return Response::make($cache_image,200, ['Content-Type' => 'image/jpeg']);

    but it alway show me Call to undefined method Intervention\Image\ImageManager::encode() could somebody help me??

    opened by ha-family 6
  • Laravel 5 Filesystem/Cloud Storage

    Laravel 5 Filesystem/Cloud Storage

    Do you have any plans to enable the use of other storage engines for the cache, perhaps utilising L5's new storage abstraction?

    It'd be useful to be able to host cached images in S3 etc. At the moment, my load balanced application caches the image on each node which is obviously not ideal.

    opened by benswinburne 5
  • PHP8.1: Opis\Closure\SerializableClosure implements the Serializable interface, which is deprecated ...

    PHP8.1: Opis\Closure\SerializableClosure implements the Serializable interface, which is deprecated ...

    Hi,

    We are getting this error on PHP8.1

    PHP message: PHP Deprecated:  Opis\Closure\SerializableClosure implements the Serializable interface, which is deprecated. Implement __serialize() and __unserialize() instead (or in addition, if support for old PHP versions is necessary)
    

    Since opis/closure has no native support for PHP8.1, is it possible to use the Laravel-fork (laravel/serializable-closure) instead of opis/closure?

    See

    • https://github.com/opis/closure/issues/107
    • https://github.com/opis/closure/issues/102
    • https://github.com/laravel/serializable-closure
    opened by nickurt 0
  • Output buffering may truncate image output

    Output buffering may truncate image output

    In some server configurations, output buffering will cause the image content to be truncated by approximately 5 rows of pixels. I confirmed that this happened with both PHP 7.4 and 8.0, using both GD and Imagick drivers.

    To verify, I recreated the original issue by using ob_start() on the same line in my local MAMP environment. Output was then truncated, and my browser showed an image corrupt message. Swapping it for the correct ob_end_clean() resolved the issue on both my development and the production machines.

    This just ensures that any automatic output buffering is turned off properly.

    opened by rk 0
  • abort() suggestion when file not found

    abort() suggestion when file not found

    In laravel, abort(404) returns a custom 404 page, which can take some time.

    Maybe https://github.com/Intervention/imagecache/blob/master/src/Intervention/Image/ImageCacheController.php - line 137 should be this instead, so it just returns one line?:

    abort( response()->json(['message' => 'Not Found!'], 404) );

    opened by iateadonut 0
  • Undefined property: GuzzleHttp\Psr7\Stream::$encoded

    Undefined property: GuzzleHttp\Psr7\Stream::$encoded

    I’m requesting a remote image and trying to cache it. Using Laravel 6.

    If I don’t cache I can manipulate the image. When using the cache I get this error: Undefined property: GuzzleHttp\Psr7\Stream::$encoded, line 318 /intervention/imagecache/src/Intervention/Image/ImageCache.php.

    opened by RicLeP 0
  • Please add Nginx config notes in README

    Please add Nginx config notes in README

    I had a problem on my live Nginx server - cache routes gave me 404.

    The issue appears when you have static resources caching enabled for media files. F.e. this config in nginx.conf file will lead to conflict with your module:

    location ~* \.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc|webp|woff|woff2)$ {
      expires max;
      access_log off;
      add_header Cache-Control "public";
    }
    

    You have to change this to exclude your {route} directory:

    # where "cache" is {route}
    location ~* ^\/(?!cache).*\.(?:jpg|jpeg|gif|png|ico|cur|gz|svg|svgz|mp4|ogg|ogv|webm|htc|webp|woff|woff2)$ {
      expires max;
      access_log off;
      add_header Cache-Control "public";
    }
    
    opened by IgorUsoltsev 1
Releases(2.4.2)
Speed up a Laravel app by caching the entire response

Speed up an app by caching the entire response This Laravel package can cache an entire response. By default it will cache all successful get-requests

Spatie 2.1k Jan 4, 2023
Caching extension for the Intervention Image Class

Intervention Image Cache extends the Intervention Image Class package to be capable of image caching functionality.

null 616 Dec 30, 2022
Auto Image & file upload, resize and crop for Laravel eloquent model using Intervention image

Laravel ImageUp The qcod/laravel-imageup is a trait which gives you auto upload, resize and crop for image feature with tons of customization. Install

QCode.in 708 Dec 22, 2022
Image Cache is a very simple PHP class that accepts an image source and will compress and cache the file, move it to a new directory, and returns the new source for the image.

NO LONGER MAINTAINED!!! Image Cache v. 1.0.0 Image Cache is a very simple PHP class that accepts an image source and will compress and cache the file,

Erik Nielsen 455 Dec 30, 2022
This Magento extension provides a Real Full Page Caching for Magento powered by Varnish with support of Session-Based information caching (Cart, Customer Accounts, ...) via ESI includes

This Magento extension provides a Real Full Page Caching (FPC) for Magento powered by Varnish with support of Session-Based information caching (Cart, Customer Accounts, ...) via ESI includes

Hugues Alary 95 Feb 11, 2022
Manipulating Photos in Laravel with Intervention Image

This is the source code behind the Laracasts Larabit: Manipulating Photos in Laravel with Intervention Image, and features all of the files and code available in that video.

Andrew Schmelyun 1 Feb 10, 2022
The Gregwar\Image class purpose is to provide a simple object-oriented images handling and caching API

Gregwar's Image class The Gregwar\Image class purpose is to provide a simple object-oriented images handling and caching API. Installation With compos

Grégoire Passault 958 Dec 29, 2022
[READ-ONLY] Easy to use Caching library with support for multiple caching backends. This repo is a split of the main code that can be found in https://github.com/cakephp/cakephp

CakePHP Caching Library The Cache library provides a Cache service locator for interfacing with multiple caching backends using a simple to use interf

CakePHP 49 Sep 28, 2022
Caching implementation with a variety of storage options, as well as codified caching strategies for callbacks, classes, and output

laminas-cache Laminas\Cache provides a general cache system for PHP. The Laminas\Cache component is able to cache different patterns (class, object, o

Laminas Project 69 Jan 7, 2023
salah eddine bendyab 18 Aug 17, 2021
A simple wrapper for PHP Intervention Library to provide a more simple interface and convenient way to convert images to webp

This package is a simple wrapper for PHP Intervention Library to provide a more simple interface and convenient way to convert images to webp - next generation format - extension, and resize them to render only needed sizes.

eyad hamza 18 Jun 28, 2022
Simple Yet Powerful PHP Caching Class

The PHP high-performance object caching system ever. phpFastCache is a high-performance, distributed object caching system, generic in nature, but intended for use in speeding up dynamic web applications by alleviating database load. phpFastCache dropped the database load to almost nothing, yielding faster page load times for users, better resource utilization. It is simple yet powerful

Khoa Bui 28 Aug 19, 2022
A Laravel Gravatar package for retrieving gravatar image URLs or checking the existance of an image.

Gravatar for Laravel 5.x, 6, 7 and 8 Installation First, pull in the package through Composer via the command line: composer require creativeorange/gr

Creativeorange 477 Dec 1, 2022
This plugin adds a new image style for the Core Image block.

This plugin adds a new image style for the Core Image block. Introduction How to use? Go to Gutenberg Editor and add a image block. e.g. Add new image

Mahesh Waghmare 3 Feb 17, 2022
WordPress plugin renames image filenames to be more SEO friendly, based on the post's data and image metadata.

=== Automatic image Rename === Contributors: wpsunshine Tags: image, images, SEO, rename, optimization Requires at least: 5.0 Tested up to: 6.2.2 Stab

null 8 Jun 11, 2023
PHP library to easily edit image with GD extension. Resize, crop, merge, draw, and many more options !

PHP Image Editor PHP library to easily edit image with GD extension. Resize, crop, merge, draw, and many more options ! ✨ Supporting ⭐ Star this repos

Franck Alary 17 Nov 13, 2022
Image manager extension for the Yii PHP framework.

yii-imagemanager Image manager extension for the Yii PHP framework. Introduction I started this project to reduce the need for boilerplate code when w

Christoffer Niska 23 Aug 28, 2020
A Formatter Class for Laravel 4 based on FuelPHP's Formatter Class

Changelog Update support for Laravel 6 & phpunit 8 Update composer.json Upgrade to PSR-4 add parameter newline, delimiter, enclosure, and escape to ex

Soapbox Innovations Inc. 249 Nov 29, 2022
Exploiting and fixing security vulnerabilities of an old version of E-Class. Project implemented as part of the class YS13 Cyber-Security.

Open eClass 2.3 Development of XSS, CSRF, SQLi, RFI attacks/defences of an older,vulnerable version of eclass. Project implemented as part of the clas

Aristi_Papastavrou 11 Apr 23, 2022
PHP Router class - A simple Rails inspired PHP router class.

PHP Router class A simple Rails inspired PHP router class. Usage of different HTTP Methods REST / Resourceful routing Reversed routing using named rou

Danny van Kooten 565 Jan 8, 2023