Skip to content
  • About
    • What is Symfony?
    • Community
    • News
    • Contributing
    • Support
  • Documentation
    • Symfony Docs
    • Symfony Book
    • Screencasts
    • Symfony Bundles
    • Symfony Cloud
    • Training
  • Services
    • Platform.sh for Symfony Best platform to deploy Symfony apps
    • SymfonyInsight Automatic quality checks for your apps
    • Symfony Certification Prove your knowledge and boost your career
    • SensioLabs Professional services to help you with Symfony
    • Blackfire Profile and monitor performance of your apps
  • Other
  • Blog
  • Download
sponsored by
  1. Home
  2. Documentation
  3. Bundles
  4. LiipImagineBundle
  5. Basic Usage

Basic Usage

Edit this page

Generally, this bundle works by applying filter sets to images from inside a template. Your filter sets are defined within the application's configuration file (often app/config/config.yml) and are comprised of a collection of filters, post-processors, and other optional parameters.

We'll learn more about post-processors and other available parameters later, but for now lets focus on how to define a small filter set comprised of a few filters.

Create Thumbnails

Before we get started, there is a small amount of configuration needed to ensure our data loaders and cache-resolvers operate correctly. Use the following configuration boilerplate.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
# app/config/config.yml

liip_imagine:

    # configure resolvers
    resolvers:

        # setup the default resolver
        default:

            # use the default web path
            web_path: ~

    # your filter sets are defined here
    filter_sets:

        # use the default cache configuration
        cache: ~

With the basic configuration in place, we'll start with an example that fulfills a common use-case: creating thumbnails. Lets assume we want the resulting thumbnails to have the following transformations applied to them:

  • Scale and crop the image to 120x90px.
  • Add a 2px black border to the scaled image.
  • Adjust the image quality to 75.

Adding onto our boilerplate from above, we need to define a filter set (which we'll name my_thumb) with two filters configured: the thumbnail and background filters.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
# app/config/config.yml

liip_imagine:
    resolvers:
        default:
            web_path: ~

    filter_sets:
        cache: ~

        # the name of the "filter set"
        my_thumb:

            # adjust the image quality to 75%
            quality: 75

            # list of transformations to apply (the "filters")
            filters:

                # create a thumbnail: set size to 120x90 and use the "outbound" mode
                # to crop the image when the size ratio of the input differs
                thumbnail: { size: [120, 90], mode: outbound }

                # create a 2px black border: center the thumbnail on a black background
                # 4px larger to create a 2px border around the final image
                background: { size: [124, 94], position: center, color: '#000000' }

You've now created a filter set called my_thumb that performs a thumbnail transformation. The thumbnail filter sizes the image to the desired width and height (120x90px), and its mode: outbound option causes the resulting image to be cropped if the input ratio differs. The background filter results in a 2px black border by creating a black canvas 124x94px in size, and positioning the thumbnail at its center.

Note

A filter set can have any number of filters defined for it. Simple transformations may only require a single filter, while more complex transformations can have any number of filters defined for them.

There are a number of additional filters, but for now you can use your newly defined my_thumb filter set immediately within a template.

1
<img src="{{ asset('/relative/path/to/image.jpg') | imagine_filter('my_thumb') }}" />
1
<img src="<?php echo $this['imagine']->filter('/relative/path/to/image.jpg', 'my_thumb') ?>" />

Behind the scenes, the bundle applies the filter(s) to the image on-the-fly when the first page request is served. The transformed image is then cached for subsequent requests. The final cached image path would be similar to /media/cache/my_thumb/relative/path/to/image.jpg.

Tip

You can prepare the cache in advance with either the commands or the message queue, or handle missing files with web server configuration. When you do that, you can use the imagine_filter_cache filter to always return a link to the final cached image.

Note

When you use the asset function to resolve image paths and have asset versioning configured, the imagine_filter tries to handle the version query string. See asset versioning for more information.

Note

Using the dev environment you might find that images are not properly rendered via the template helper. This is often caused by having intercept_redirect enabled in your application configuration. To ensure images are rendered, it is strongly suggested to disable this option:

1
2
3
4
# app/config/config_dev.yml

web_profiler:
    intercept_redirects: false

Runtime Options

Sometimes, you may have a filter defined that fulfills 99% of your usage scenarios. Instead of defining a new filter for the erroneous 1% of cases, you may instead choose to alter the behavior of a filter at runtime by passing the template helper an options array.

1
2
3
{% set runtimeConfig = {"thumbnail": {"size": [50, 50] }} %}

<img src="{{ asset('/relative/path/to/image.jpg') | imagine_filter('my_thumb', runtimeConfig) }}" />
1
2
3
4
5
6
7
8
9
<?php
$runtimeConfig = [
    "thumbnail" => [
        "size" => [50, 50]
    ]
];
?>

<img src="<?php $this['imagine']->filter('/relative/path/to/image.jpg', 'my_thumb', $runtimeConfig) ?>" />

Path Resolution

Sometimes you need to resolve the image path returned by this bundle for a filtered image. This can be achieved using Symfony's console binary or programmatically from within a controller or other piece of code.

Resolve with the Console

You can resolve an image URL using the console command liip:imagine:cache:resolve. The only required argument is one or more relative image paths (which must be separated by a space).

1
$ php bin/console liip:imagine:cache:resolve relative/path/to/image1.jpg relative/path/to/image2.jpg

Additionally, you can use the --filters option to specify which filter you want to resolve for (if the --filters option is omitted, all available filters will be resolved).

1
$ php bin/console liip:imagine:cache:resolve relative/path/to/image1.jpg --filters=my_thumb

Resolve Programmatically

You can resolve the image URL in your code using the getBrowserPath method of the Liip\ImagineBundle\Imagine\Cache\CacheManager service. Assuming you already have the service assigned to a variable called $imagineCacheManager, you would run:

1
$imagineCacheManager->getBrowserPath('/relative/path/to/image.jpg', 'my_thumb');

Often, you need to perform this operation in a controller.

In a controller, this can look as follows:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php

namespace App\Controller;

use Liip\ImagineBundle\Imagine\Cache\CacheManager;

class YourController
{
    public function yourControllerMethod(CacheManager $imagineCacheManager)
    {
        /** @var string */
        $resolvedPath = $imagineCacheManager->getBrowserPath('/relative/path/to/image.jpg', 'my_thumb');

        // ...
    }
}

WebP image format

The WebP format better optimizes the quality and size of the compressed image compared to JPEG and PNG. Google strongly recommends using this format.

WebP for all

If you can ignore old browsers that do not support the WebP format, then you can configure the generation of all images in the WebP format.

1
2
3
4
5
# app/config/config.yml

liip_imagine:
    default_filter_set_settings:
        format: webp

Use WebP if supported

However, not all browsers support the WebP format, and for compatibility with all browsers it is recommended to return images in their original format for those browsers that do not support WebP. This means that you need to store 2 versions of the image. One in WebP format and the other in original format. Remember that this almost doubles the amount of used space on the server for storing filtered images.

1
2
3
4
5
6
7
8
9
10
11
12
# app/config/config.yml

liip_imagine:
    # configure webp
    webp:
        generate: true

    # example filter
    filter_sets:
        thumbnail_web_path:
            filters:
                thumbnail: { size: [223, 223], mode: inset }

If browser supports WebP, the request https://localhost/media/cache/resolve/thumbnail_web_path/images/cats.jpeg will be redirected to https://localhost/media/cache/thumbnail_web_path/images/cats.jpeg.webp otherwise to https://localhost/media/cache/thumbnail_web_path/images/cats.jpeg

Optimize Firewall Configuration

For most applications, requests to the filter controllers (the /media/cache/resolve path) do not require Symfony to load the authenticated user data from the session. To optimize performance, you can disable the authentication system by defining a firewall for these controllers using the following code snippet:

1
2
3
4
5
6
7
# app/config/security.yml

security:
    firewalls:
        image_resolver:
            pattern: ^/media/cache/resolve
            security: false

Note

Using an unsecured connection (non HTTPS) on your site can cause problems with caching the resolved paths for users, which can lead to the fact that users whose browser does not support WebP will serve a picture in WebP format. You can fix this problem by changing the redirect code from 301 (Moved Permanently) to 302 (Moved Temporarily).

1
2
3
4
5
# app/config/config.yml

liip_imagine:
    controller:
        redirect_response_code: 302

Client side resolving

For better performance, you can use the <picture> tag to resolve a supported image formats on client-side in the browser. This will complicate the HTML code and require registering two identical filters that generate images in different formats.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# app/config/config.yml

liip_imagine:
    filter_sets:
        my_thumb_jpeg:
            format: jpeg
            quality: 80
            filters:
                thumbnail: { size: [223, 223], mode: inset }
        my_thumb_webp:
            format: webp
            quality: 100
            filters:
                thumbnail: { size: [223, 223], mode: inset }
1
2
3
4
5
<picture>
  <source srcset="{{ '/relative/path/to/image.jpg' | imagine_filter('my_thumb_webp') }}" type="image/webp">
  <source srcset="{{ '/relative/path/to/image.jpg' | imagine_filter('my_thumb_jpeg') }}" type="image/jpeg">
  <img src="{{ '/relative/path/to/image.jpg' | imagine_filter('my_thumb_jpeg') }}" alt="Alt Text!">
</picture>
This work, including the code samples, is licensed under a Creative Commons BY-SA 3.0 license.
TOC
    Version
    Online exam, become Sylius certified today

    Online exam, become Sylius certified today

    Make sure your project is risk free

    Make sure your project is risk free

    Version:

    Table of Contents

    • Create Thumbnails
    • Runtime Options
    • Path Resolution
      • Resolve with the Console
      • Resolve Programmatically
    • WebP image format
      • WebP for all
      • Use WebP if supported
      • Optimize Firewall Configuration
      • Client side resolving

    Symfony footer

    Avatar of Adam Bramley, a Symfony contributor

    Thanks Adam Bramley for being a Symfony contributor

    1 commit • 4 lines changed

    View all contributors that help us make Symfony

    Become a Symfony contributor

    Be an active part of the community and contribute ideas, code and bug fixes. Both experts and newcomers are welcome.

    Learn how to contribute

    Symfony™ is a trademark of Symfony SAS. All rights reserved.

    • What is Symfony?

      • What is Symfony?
      • Symfony at a Glance
      • Symfony Components
      • Symfony Releases
      • Security Policy
      • Logo & Screenshots
      • Trademark & Licenses
      • symfony1 Legacy
    • Learn Symfony

      • Symfony Docs
      • Symfony Book
      • Reference
      • Bundles
      • Best Practices
      • Training
      • eLearning Platform
      • Certification
    • Screencasts

      • Learn Symfony
      • Learn PHP
      • Learn JavaScript
      • Learn Drupal
      • Learn RESTful APIs
    • Community

      • Symfony Community
      • SymfonyConnect
      • Events & Meetups
      • Projects using Symfony
      • Contributors
      • Symfony Jobs
      • Backers
      • Code of Conduct
      • Downloads Stats
      • Support
    • Blog

      • All Blog Posts
      • A Week of Symfony
      • Case Studies
      • Cloud
      • Community
      • Conferences
      • Diversity
      • Living on the edge
      • Releases
      • Security Advisories
      • Symfony Insight
      • Twig
      • SensioLabs Blog
    • Services

      • SensioLabs services
      • Train developers
      • Manage your project quality
      • Improve your project performance
      • Host Symfony projects

      Powered by

    Follow Symfony