Convert Figma logo to code with AI

liip logoLiipImagineBundle

Symfony Bundle to assist in image manipulation using the imagine library

1,660
378
1,660
71

Top Related Projects

4,416

PHP Object Oriented image manipulation library

A simple Symfony bundle to ease file uploads with ORM entities and ODM documents.

1,236

Manipulate images with an expressive API

2,547

Wonderfully easy on-demand image manipulation library with an HTTP based API.

Quick Overview

LiipImagineBundle is a Symfony bundle that provides an easy and flexible way to manipulate images in web applications. It integrates with Symfony's filesystem and cache components, offering on-the-fly image processing and caching capabilities.

Pros

  • Seamless integration with Symfony framework
  • Supports various image processing operations (resize, crop, rotate, etc.)
  • Flexible caching mechanisms for improved performance
  • Extensible architecture allowing custom filters and loaders

Cons

  • Limited to Symfony applications
  • Requires additional setup for certain image processing libraries
  • Performance may be impacted for large-scale image processing tasks
  • Documentation can be overwhelming for beginners

Code Examples

  1. Basic image resizing:
$dataManager = $this->get('liip_imagine.data.manager');
$filterManager = $this->get('liip_imagine.filter.manager');

$image = $dataManager->find('thumbnail', 'path/to/image.jpg');
$response = $filterManager->applyFilter($image, 'my_thumb');

return $response;
  1. Defining a custom filter:
# config/packages/liip_imagine.yaml
liip_imagine:
    filter_sets:
        my_thumb:
            quality: 75
            filters:
                thumbnail: { size: [120, 90], mode: outbound }
  1. Using filters in Twig templates:
<img src="{{ asset('path/to/image.jpg') | imagine_filter('my_thumb') }}" />

Getting Started

  1. Install the bundle:

    composer require liip/imagine-bundle
    
  2. Enable the bundle in config/bundles.php:

    return [
        // ...
        Liip\ImagineBundle\LiipImagineBundle::class => ['all' => true],
    ];
    
  3. Configure the bundle in config/packages/liip_imagine.yaml:

    liip_imagine:
        resolvers:
            default:
                web_path: ~
        filter_sets:
            cache: ~
            my_thumb:
                quality: 75
                filters:
                    thumbnail: { size: [120, 90], mode: outbound }
    
  4. Clear the cache and you're ready to use LiipImagineBundle in your Symfony application.

Competitor Comparisons

4,416

PHP Object Oriented image manipulation library

Pros of Imagine

  • Standalone PHP image manipulation library, not tied to any framework
  • More flexible and can be used in various PHP projects
  • Provides a simpler, more straightforward API for image operations

Cons of Imagine

  • Lacks built-in caching mechanisms
  • Doesn't provide out-of-the-box integration with web frameworks
  • Requires more manual configuration for advanced use cases

Code Comparison

LiipImagineBundle:

$imagine = $this->container->get('liip_imagine.cache.manager');
$cachedImage = $imagine->getBrowserPath('path/to/image.jpg', 'my_thumb');

Imagine:

$imagine = new Imagine\Gd\Imagine();
$image = $imagine->open('path/to/image.jpg');
$image->resize(new Box(120, 90))->save('path/to/thumbnail.jpg');

LiipImagineBundle is a Symfony bundle that integrates Imagine into the Symfony framework, providing caching and easy configuration through YAML files. It's ideal for Symfony projects requiring image manipulation.

Imagine, on the other hand, is a standalone library that offers more flexibility for use in various PHP projects. It provides a lower-level API for image manipulation but requires more manual setup for caching and integration with web frameworks.

Choose LiipImagineBundle for Symfony projects with straightforward image manipulation needs, and Imagine for more flexibility in non-Symfony projects or when more control over the image processing pipeline is required.

A simple Symfony bundle to ease file uploads with ORM entities and ODM documents.

Pros of VichUploaderBundle

  • Focuses on file uploads and management, providing a more specialized solution
  • Offers automatic file naming and organization based on entity properties
  • Integrates well with Doctrine ORM for seamless file handling in entities

Cons of VichUploaderBundle

  • Limited image manipulation capabilities compared to LiipImagineBundle
  • Requires more manual configuration for advanced file handling scenarios
  • Less flexibility in terms of storage adapters and file systems

Code Comparison

VichUploaderBundle:

use Vich\UploaderBundle\Mapping\Annotation as Vich;

/**
 * @Vich\Uploadable
 */
class Product
{
    /**
     * @Vich\UploadableField(mapping="product_image", fileNameProperty="imageName")
     */
    private $imageFile;
}

LiipImagineBundle:

use Symfony\Component\Routing\Annotation\Route;

/**
 * @Route("/media/cache/resolve/{filter}/{path}", name="liip_imagine_filter")
 */
public function filterAction($filter, $path)
{
    return $this->get('liip_imagine.controller')->filterAction($this->request, $path, $filter);
}

The code examples showcase the different approaches: VichUploaderBundle focuses on entity-level file management, while LiipImagineBundle emphasizes image manipulation and caching through routes and controllers.

1,236

Manipulate images with an expressive API

Pros of Image

  • Lightweight and standalone PHP package, not tied to any specific framework
  • Simple and intuitive API for common image manipulation tasks
  • Supports modern PHP versions (7.4+) and follows PSR-12 coding standards

Cons of Image

  • Limited to basic image operations compared to LiipImagineBundle's extensive features
  • Lacks integration with Symfony's caching and asset management systems
  • Does not provide built-in support for on-the-fly image generation or optimization

Code Comparison

LiipImagineBundle (Symfony configuration):

liip_imagine:
    filter_sets:
        my_thumb:
            filters:
                thumbnail: { size: [120, 90], mode: outbound }
                background: { size: [124, 94], position: center, color: '#000000' }

Image (PHP code):

use Spatie\Image\Image;

Image::load('image.jpg')
    ->fit(Manipulations::FIT_CROP, 120, 90)
    ->background('black')
    ->save('thumb.jpg');

Both libraries offer image manipulation capabilities, but LiipImagineBundle is more tightly integrated with Symfony and provides a wider range of features. Image, on the other hand, offers a simpler, framework-agnostic approach for basic image processing tasks.

2,547

Wonderfully easy on-demand image manipulation library with an HTTP based API.

Pros of Glide

  • Standalone library, not tied to any framework
  • Supports real-time image processing and caching
  • Simple URL-based API for image manipulation

Cons of Glide

  • Less integrated with Symfony ecosystem
  • Fewer built-in filters and effects compared to LiipImagineBundle
  • May require more setup for advanced use cases

Code Comparison

LiipImagineBundle (Symfony configuration):

liip_imagine:
    filter_sets:
        my_thumb:
            quality: 75
            filters:
                thumbnail: { size: [120, 90], mode: outbound }

Glide (PHP usage):

$server = League\Glide\ServerFactory::create([
    'source' => 'path/to/source/folder',
    'cache' => 'path/to/cache/folder',
]);
$server->outputImage('image.jpg', ['w' => 120, 'h' => 90, 'fit' => 'crop']);

Both libraries offer powerful image manipulation capabilities, but LiipImagineBundle is more tightly integrated with Symfony and provides a configuration-based approach. Glide, on the other hand, offers a more flexible, standalone solution with a simple URL-based API for image processing. The choice between the two depends on the specific project requirements and the preferred development ecosystem.

Convert Figma logo designs to code with AI

Visual Copilot

Introducing Visual Copilot: A new AI model to turn Figma designs to high quality code using your components.

Try Visual Copilot

README

LiipImagineBundle

PHPUnitPHP-CS-FixerCoverageDownloadsRelease
PHPUnitPHP-CS-FixerCoverageDownloadsLatest 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.