Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel 5 intervention-image / intervention-cache: flexible url / routing

Fiddling around with Intervention 2.0 in Laravel 5. What I want is to manipulate images (size and cropping) and use Interventions Image Caching to cache the images. What I basically try to achieve is the functionality of good old (and insecure) timthumb.php.

I started using this as an example:

// routes.php
Route::get('imager/{src?}', function ($src)
{
    $cacheimage = Image::cache(function($image) use ($src) {
        return $image->make("files/image/".$src)->resize(100,50);
    }, 10, true);

    return Response::make($cacheimage, 200, array('Content-Type' => 'image/jpeg'));
});

When I load an image like so:

// template
<img src="{{"imager/image.jpg"}}"/>

It works fine.

But... In my situation images can be located in different (sub) directories, sometimes multiple levels deep. They are maintained in my CMS by their webmasters.

examples:

  • files/images/image.jpg
  • files/images/headers/image.jpg
  • files/images/background/color/image.jpg
  • img/common/logo.png

These image url's are loaded from a mysql table record.

When such an images loads:

// template
<img src="{{"imager/files/images/image.jpg"}}"/>

The route is not working anymore. After all, files, images and images.jpg are all url segments and the amount of them could differ.

The image url (Bold) should be handled as one variable:

Route::get('imager/files/images/image.jpg', function ($src = false)

Then I should be able to pass the sizing and cropping parameters off course. Because the img url length could vary I assume I could pass the parameters with a query like ?w=100&h=50&c=true or something?


Update

When I use a query parameter for the image url:

Route::get('imager', function ()
{
    $src = Input::get('src', 1);

    $cacheimage = Image::cache(function($image) use ($src) {
        return $image->make($src)->resize(100,100);
    }, 1, false); // one minute cache expiry

    return Response::make($cacheimage, 200, array('Content-Type' => 'image/jpeg'));
});

// template
<img src="{{"imager?src=files/images/image.jpg"}}"/>

This works.

like image 302
Klaaz Avatar asked Mar 17 '15 12:03

Klaaz


1 Answers

It is simple. You just have to tell Laravel that your image parameter consists of letters, slash, dash, underscore and dot ('[A-Za-z0-9\/\.\-\_]+'), because by default the framework matches everything but the slash /.

Route::get('imager/{image?}', function($src) {

    $cachedImage = Image::cache(function($image) use ($src) {
        return $image->make($src)->resize(100,100);
    }, 1, false);

    return Response::make($cachedImage, 200, ['Content-Type' => 'image/jpeg']);
})->where('image', '[A-Za-z0-9\/\.\-\_]+');

You can find out more about parameter binding in the documentation.

like image 65
Sh1d0w Avatar answered Sep 28 '22 19:09

Sh1d0w