• Stars
    star
    1,661
  • Rank 28,132 (Top 0.6 %)
  • Language
    PHP
  • License
    MIT License
  • Created about 13 years ago
  • Updated 4 months ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

Symfony Bundle to assist in image manipulation using the imagine library

LiipImagineBundle

PHPUnit PHP-CS-Fixer Coverage Downloads Release
PHPUnit PHP-CS-Fixer Coverage Downloads Latest Stable Version

This bundle provides an image manipulation abstraction toolkit for Symfony-based projects.

Overview

Example

Suppose you defined a my_thumb filter set, which can be configured to perform any number of different transformations. The simplest invocation would be to pipe the path of your image to the provided imagine_filter Twig filter.

<img src="{{ asset('/relative/path/to/image.jpg') | imagine_filter('my_thumb') }}" />

Contributor Code of Conduct

This project is released with a Contributor Code of Conduct. By participating in this project you agree to abide by its terms.

Attribution

  • Thanks to the many contributors who have dedicated their time and code to this project.

  • The standalone PHP Imagine Library is used by this bundle for image transformations.

  • This package was forked from AvalancheImagineBundle with the goal of making the code more extensible. Reference AvalancheImagineBundle#25 for additional information on the reasoning for this fork.

Setup

Installation

Using this package is similar to all Symfony bundles. The following steps must be performed

  1. Download the Bundle
  2. Enable the Bundle
  3. Register the Routes

Detailed setup instructions can be found in the installation chapter of the documentation.

Configuration

Detailed information on all available configuration options can be found in the configuration chapter of the documentation.

Usage Primer

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 simple 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 boilerplate in your configuration file.

# 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.

# 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 (in this example, 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 complex transformations can have an unlimited 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.

For Twig-based template, use:

<img src="{{ asset('/relative/path/to/image.jpg') | imagine_filter('my_thumb') }}" />

Or, for PHP-based template, use:

<img src="<?php $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.

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:

# app/config/config_dev.yml

web_profiler :
    intercept_redirects : false

Runtime Options

Sometime, 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.

For Twig-based template, use:

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

<img src="{{ asset('/relative/path/to/image.jpg') | imagine_filter('my_thumb', runtimeConfig) }}" />

Or, for PHP-based template, use:

<?php
$runtimeConfig = array(
    "thumbnail" => array(
        "size" => array(50, 50)
    )
);
?>

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

Path Resolution

Sometime you need to resolve the image path returned by this bundle for a filtered image. This can easily 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).

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

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

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

Resolve Programmatically

You can resolve the image URL in your code using the getBrowserPath method of the liip_imagine.cache.manager service. Assuming you already have the service assigned to a variable called $imagineCacheManager, you would run:

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

Often, you need to perform this operation in a controller. Assuming your controller inherits from the base Symfony controller, you can take advantage of the inherited get method to request the liip_imagine.cache.manager service, from which you can call getBrowserPath on a relative image path to get its resolved location.

/** @var CacheManager */
$imagineCacheManager = $this->get('liip_imagine.cache.manager');

/** @var string */
$resolvedPath = $imagineCacheManager->getBrowserPath('/relative/path/to/image.jpg', 'my_thumb');

Filters

This bundle provides a set of built-in filters and you may easily define your own filters as well. Reference the filters chapter from our documentation.

Use as a Service

If you need to use your defined "filter sets" from within your controller, you can fetch this bundle's FilterService from the service container to do the heavy lifting for you.

<?php

class MyController extends Controller
{
    public function indexAction()
    {
        /** @var FilterService */
        $imagine = $this
            ->container
            ->get('liip_imagine.service.filter');

        // 1) Simple filter, OR
        $resourcePath = $imagine->getUrlOfFilteredImage('uploads/foo.jpg', 'my_thumb');
        
        // 2) Runtime configuration
        $runtimeConfig = [
            'thumbnail' => [
                'size' => [200, 200]
            ],
        ];
        $resourcePath = $imagine->getUrlOfFilteredImageWithRuntimeFilters(
            'uploads/foo.jpg',
            'my_thumb',
            $runtimeConfig
        );

        // ..
    }
}

?>

Data Roots

By default, Symfony's web/ directory is registered as a data root to load assets from. For many installations this will be sufficient, but sometime you may need to load images from other locations. To do this, you must set the data_root parameter in your configuration (often located at app/config/config.yml).

liip_imagine:
    loaders:
        default:
            filesystem:
                data_root: /path/to/source/images/dir

As of version 1.7.2 you can register multiple data root paths, and the file locator will search each for the requested file.

liip_imagine:
    loaders:
        default:
            filesystem:
                data_root:
                    - /path/foo
                    - /path/bar

As of version 1.7.3 you ask for the public resource paths from all registered bundles to be auto-registered as data roots. This allows you to load assets from the Resources/public folders that reside within the loaded bundles. To enable this feature, set the bundle_resources.enabled configuration option to true.

liip_imagine:
    loaders:
        default:
            filesystem:
                bundle_resources:
                    enabled: true

If you want to register some of the Resource/public folders, but not all, you can do so by blacklisting the bundles you don't want registered or whitelisting the bundles you do want registered. For example, to blacklist (not register) the bundles "FooBundle" and "BarBundle", you would use the following configuration.

liip_imagine:
    loaders:
        default:
            filesystem:
                bundle_resources:
                    enabled: true
                    access_control_type: blacklist
                    access_control_list:
                        - FooBundle
                        - BarBundle

Alternatively, if you want to whitelist (only register) the bundles "FooBundle" and "BarBundle", you would use the following configuration.

liip_imagine:
    loaders:
        default:
            filesystem:
                bundle_resources:
                    enabled: true
                    access_control_type: whitelist
                    access_control_list:
                        - FooBundle
                        - BarBundle

Permissions

Image locations must be readable by your web server. On a system that supports setfacl (such as Linux/BSD), use

HTTPDUSER=`ps axo user,comm | grep -E '[a]pache|[h]ttpd|[_]www|[w]ww-data|[n]ginx' | grep -v root | head -1 | cut -d\  -f1`

sudo setfacl -R -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX /path/to/source/images/dir

sudo setfacl -dR -m u:"$HTTPDUSER":rwX -m u:`whoami`:rwX /path/to/source/images/dir

See the Symfony Permissions documentation for commands compatible with macOS and other environments.

Using Apache

You need to grant read access for Apache by adding the following to your Apache VHost configuration

<VirtualHost *:80>
    <!-- Rest of directives like DocumentRoot or ServerName -->

    Alias /FavouriteAlias /path/to/source/images/dir
    <Directory "/path/to/source/images/dir">
        AllowOverride None
        Allow from All
    </Directory>
</VirtualHost>

Alternatively, you can place the directive in a separate file within your project, and include it within your Apache VHost configuration. For example, you can create the file app/config/apache/photos.xml and add the following to your VHost file

<VirtualHost *:80>
    <!-- Rest of directives like DocumentRoot or ServerName -->

    Include "/path/to/your/project/app/config/apache/photos.xml"
</VirtualHost>

This method keeps the file with the rest of your code, allowing you to change it easily or create different environment-dependent configuration files.

Once you have configured Apache properly, the relative path to an image with the following absolute path /path/to/source/images/dir/logo.png must be /FavouriteAlias/logo.png.

Documentation

For more detailed information about the features of this bundle, refer to the documentation.

More Repositories

1

LiipFunctionalTestBundle

Some helper classes for writing functional tests in Symfony
PHP
639
star
2

TheA11yMachine

The A11y Machine is an automated accessibility testing tool which crawls and tests pages of any web application to produce detailed reports.
JavaScript
620
star
3

LiipMonitorBundle

Integrates the LiipMonitor library into Symfony
PHP
469
star
4

RMT

RMT is a handy tool to help releasing new version of your software
PHP
451
star
5

php-osx

DEPRECATED: See https://php-osx.liip.ch/ for details. The uploader and website for the PHP 5 package for OS X 10.6 built with https://github.com/liip/build-entropy-php
PHP
329
star
6

LiipThemeBundle

Provides theming support for Symfony bundles
PHP
291
star
7

bootstrap-blocks-wordpress-plugin

Bootstrap Gutenberg Blocks for WordPress
PHP
279
star
8

sheriff

Conditional marshalling for Go
Go
244
star
9

LiipHelloBundle

[DEPRECATED] Alternative Hello World Bundle for Symfony2 using several FriendsOfSymfony Bundles
PHP
201
star
10

LiipTestFixturesBundle

This bundles enables efficient loading of Doctrine fixtures in functional test-cases for Symfony applications
PHP
165
star
11

serializer

A PHP serializer that generates PHP code for maximum performance
PHP
128
star
12

LiipCacheControlBundle

DEPRECATED! This bundle is superseded by FOSHttpCacheBundle. A migration guide is in the README of LiipCacheControlBundle
PHP
108
star
13

kanbasu

A lightweight CSS framework written in Sass.
SCSS
92
star
14

LiipDoctrineCacheBundle

[DEPRECATED] use https://github.com/doctrine/DoctrineCacheBundle
PHP
71
star
15

LiipMagentoBundle

[DEPRECATED] Proof of concept for integrating Magento into Symfony2 applications
PHP
67
star
16

LiipMonitor

Deprecated: Generic PHP library to run application health checks
PHP
61
star
17

Radios

An mp3 streaming Application for the iPhone and the iPad
Objective-C
59
star
18

drifter

Drifter is a framework to help provision developer boxes using Ansible and Vagrant
HTML
57
star
19

chusho

A library of bare & accessible UI components and tools for Vue.js 3
TypeScript
55
star
20

SEO-keywords-generator

Keyword generator providing multiple commands in order to manage keyphrases for SEO monitoring tools such as AWRCloud
Python
52
star
21

LiipUrlAutoConverterBundle

[DEPRECATED] This bundle will add a Twig Extension for templates with a new filter for automatically converting urls and emails in a string to html links
PHP
50
star
22

extend-block-example-wp-plugin

Example how to extend an existing Gutenberg block in WordPress
JavaScript
49
star
23

packaging

deb and rpm packaging solution for php projects
PHP
49
star
24

styleguide-starterkit

A starterkit to create styleguides with Fractal and Webpack.
JavaScript
37
star
25

LiipSearchBundle

[DEPRECATED] Google XML API for searching is discontinued
PHP
35
star
26

LiipProcessManager

Provides a simple locking mechanism based on UNIX process id's written to a "PID file".
PHP
33
star
27

LiipVieBundle

[DEPRECATED] in favor of SymfonyCmfCreateBundle
JavaScript
32
star
28

viewmodel-savedstate-helpers

Easily save your Android ViewModel state with Kotlin
Kotlin
32
star
29

fanci

Fanci is a lightweight node module to extract, rename and transform JSON based on a template
JavaScript
30
star
30

LiipContainerWrapperBundle

[DEPRECATED] Don't screw DI by just injecting everything.
PHP
29
star
31

LiipCodeBundle

[DEPRECATED] A set of Symfony2 console commands to help developers deal with the various ways of identifying classes, templates, bundles, services, etc. Provides console commands to find their file path or class, as well as editor shortcuts.
PHP
26
star
32

LiipTranslationBundle

Tools for translation management
PHP
25
star
33

guess-the-liiper-ios

Guess the Liiper iOS version made with React Native
JavaScript
25
star
34

dockerbox

A small vagrant based docker box for using docker on OS X and Windows (based on https://github.com/phusion/open-vagrant-boxes)
Shell
25
star
35

packager

Lightweight package installer written in python
Python
22
star
36

LiipXsltBundle

[DEPRECATED] Renderer for XSLT templates in Symfony2 (not actively maintained)
PHP
20
star
37

LiipHyphenatorBundle

[Deprecated] Adds support to Symfony for hyphenating long words using the Org_Heigl_Hyphenator library.
PHP
20
star
38

SweetPreferences

Add syntactic sugar to your Android SharedPreferences
Kotlin
19
star
39

wrench

wrench: a CLI tool for Passbolt
Python
19
star
40

barcode.js

POC for a JavaScript barcode reader, blog post to follow
JavaScript
19
star
41

django-ansible

Deploy Django projects generated by liip/django-template with Ansible
Python
18
star
42

animate-blocks-wordpress-plugin

Animate Gutenberg blocks plugin for WordPress
JavaScript
18
star
43

presence

Presence shows you the availabilities of your set up team by analyzing their Google Calendar
PHP
18
star
44

django-template

Project template for Django projects
Python
17
star
45

metadata-parser

A PHP metadata parser for domain models
PHP
16
star
46

commit-hook-email

GitLab and Github Commit Email Hook
PHP
16
star
47

DataAggregator

[DEPRECATED] The data aggregator cumulates/filters information provided by one or more loader and routes them to one or more persistence layers.
PHP
16
star
48

magento-xhprof

[In Development] Profile Magento with XHProf
PHP
15
star
49

SwissGovernmentChatbots

15
star
50

bund-drupal-starterkit

PHP
14
star
51

styleguide

Liip Web Styleguide
SCSS
14
star
52

roger-q

Tool to work with RabbitMQ queues, including commands to dump, deduplicate and publish messages
PHP
14
star
53

liip10yearsgame

Jump and run through Liip's 10 year history
JavaScript
13
star
54

ckanext-ddi

CKAN extension for DDI, developed for the World Bank
Python
12
star
55

LiipSoapRecorderBundle

[DEPRECATED] Recorder/Player for SOAP communications
PHP
12
star
56

pontsun

The Liip docker local development orchestrator
12
star
57

wp-tyk-dev-portal

A WordPress plugin that adds a developer portal for a Tyk API Gateway
PHP
12
star
58

LiipMultiplexBundle

[DEPRECATED] Symfony2 controller that allows calling multiple URL's in one request as well as JSON-ifying any controller
PHP
12
star
59

LiipRokkaImagineBundle

integration between LiipImagineBundle and rokka.io
PHP
11
star
60

LiipKit

LiipKit regroups usefull classes/extensions used in many applications
Swift
11
star
61

LiipDrupalConnectorModule

An abstraction layer between the procedural world of Drupal and OOP.
PHP
11
star
62

serializer-jms-adapter

An adapter to make liip/serializer a drop-in replacement for jms/serializer
PHP
10
star
63

LiipFormTranslationChoiceBundle

[DEPRECATED] A Symfony2 bundle that provides a form widget and a validator that work with translation domains
PHP
10
star
64

packaging_demo

A demo project for the packaging solution at http://github.com/liip/packaging
PHP
9
star
65

LiipOneallBundle

[DEPRECATED] Symfony2 Bundle to integrate oneall.com
PHP
9
star
66

oc-blocks-theme

OctoberCMS theme that demonstrates the use of repeater groups to assemble static pages with customizable building blocks.
HTML
9
star
67

taxi-zebra

Zebra backend for Taxi
Python
8
star
68

niweaapp

The Tages-Anzeiger iPas App done in Niwea aka HTML5/CSS/JS
JavaScript
8
star
69

directus-utilities

Utility library for directus
TypeScript
8
star
70

frctl-twig

frctl-twig is an PHP Twig adapter for Fractal consisting of an NPM and a Composer package.
PHP
8
star
71

LiipFoxycartBundle

[DEPRECATED] Symfony Foxycart integration Bundle
PHP
8
star
72

discourse-multilingual-support

Provide some tools to have a better multilingual support on Discourse
Ruby
8
star
73

wrapper-block-example-wp-plugin

This is a WordPress plugin which shows how to create a wrapper block for Gutenberg.
JavaScript
7
star
74

e2e-tests-example-wp-plugin

Example how to write E2E tests for a Gutenberg block in WordPress
JavaScript
7
star
75

bower-lockfile-resolver

adds a missing feature of bower: a lockfile with all pacakages versions pinned
JavaScript
6
star
76

bund_ds

Vue
6
star
77

magerant

Magento Vagrant Setup (powered by Ansible)
Shell
6
star
78

jelapi

A Jelastic API Python library
Python
6
star
79

requests_gpgauthlib

A GPGAuth Client in Python
Python
5
star
80

ckan-vagrant

Vagrant based CKAN development environment
Ruby
5
star
81

LiipDrupalCrudAdminModule

The idea behind this module is to provide a most forward standard implementation to handle CRUD operations.
PHP
5
star
82

storybook-starterkit

A starterkit to create styleguides with Storybook and Twig.
JavaScript
5
star
83

directus-extension-gzip-hook

Directus extension gzip hook
TypeScript
4
star
84

liip-cookbooks

4
star
85

OpenLayersOfflineDemo

Demonstrate the offline storage with OpenLayers
JavaScript
4
star
86

fabliip

Set of Fabric functions to help deploying websites.
Python
4
star
87

Okapi

Okapi is a small framework for building web applications. It's built on PHP and XSLT and is fantastic for integration with REST web services.
PHP
4
star
88

html2kirby

Convert HTML markup to Kirby Markup
Python
4
star
89

liip-magento-shared

Liip Magento Shared
PHP
4
star
90

Backbone.localStorageSync

A caching layer between the client and server
JavaScript
4
star
91

Sodium.Xamarin

Xamarin compatible wrapper for libsodium
C#
3
star
92

magento-order-email-jsonld

PHP
3
star
93

magento-config-search

PHP
3
star
94

LiipDrupalRegistryModule

This module provides an API to store key/value pairs of information.
PHP
3
star
95

LiipTeraWurflBundle

[DEPRECATED] Symfony2 Bundle for the wurfl user agent. Not working! For reasons why check the url below ..
PHP
3
star
96

kanbasu-vue

Kanbasu components as Vue components
JavaScript
3
star
97

bund_drupal_starterkit_theme

CSS
3
star
98

smoke-detector

🚭 Allow us to be notified when there is smoke in the office.
Python
3
star
99

ushahidi-plugins-mobile

Mobile Accessible Version of Ushahidi
PHP
3
star
100

image-selector-example-wp-plugin

Example how to create an image selector for a Gutenberg block in WordPress
JavaScript
3
star