PHPackages                             croustille/twill-image - PHPackages - PHPackages  [Skip to content](#main-content)[PHPackages](/)[Directory](/)[Categories](/categories)[Trending](/trending)[Leaderboard](/leaderboard)[Changelog](/changelog)[Analyze](/analyze)[Collections](/collections)[Log in](/login)[Sign up](/register)

1. [Directory](/)
2. /
3. [Image &amp; Media](/categories/media)
4. /
5. croustille/twill-image

ActiveLibrary[Image &amp; Media](/categories/media)

croustille/twill-image
======================

v2.1.0(1y ago)3262916[2 PRs](https://github.com/area17/twill-image/pulls)Apache-2.0PHPPHP &gt;=7.2.5CI failing

Since Apr 29Pushed 1y ago3 watchersCompare

[ Source](https://github.com/area17/twill-image)[ Packagist](https://packagist.org/packages/croustille/twill-image)[ RSS](/packages/croustille-twill-image/feed)WikiDiscussions 2.x Synced 1mo ago

READMEChangelog (7)Dependencies (6)Versions (31)Used By (0)

Twill Image
===========

[](#twill-image)

Twill Image is a package designed to work with [Twill](https://twill.io) to display responsive images easily on your site. It leverages Twill's image processing capabilities and adds modern lazy-loading techniques. It supports responsive images, art direction and fixed width images.

- `` with multiple `` elements
- Twill's low-quality placeholder (LQIP)
- Art direction (multiple crops)
- WebP and JPEG support
- Native lazy loading with `loading='lazy'`
- Support custom CSS classes to use with Tailwind CSS

Contents
--------

[](#contents)

- [Installation](#installation)
    - [Configuration file](#configuration-file)
- [Usage](#usage)
    - [The `Image` model](#the-image-,model)
        - [Available methods](#available-methods)
            - [`crop`](#crop)
            - [`width`](#width)
            - [`height`](#height)
            - [`sources`](#sources)
            - [`sizes`](#sizes)
            - [`columns`](#columns)
            - [`srcSetWidths`](#srcSetWidths)
            - [`preset`](#preset)
            - [`render`](#render)
            - [`toArray`](#toArray)
    - [The facade `render` method](#the-facade-render-method)
        - [List of arguments](#list-of-arguments)
        - [Examples](#examples)
- [Configuration](#configuration)
    - [Presets](#presets)
    - [List of options](#list-of-options)
- [Frontend breakpoints and grid structure](#frontend-breakpoints-and-grid-structure)
    - [`columns` example](#columns-example)
        - [`columns` preset](#columns-preset)
        - [`columns` output](#columns-output)
    - [`columns` custom class](#columns-custom-class)
- [Art directed images](#art-directed-images)
- [Multiple medias](#multiple-medias)

Installation
------------

[](#installation)

Install the package to your existing Twill project with Composer.

```
composer require area17/twill-image

```

### Configuration file

[](#configuration-file)

The configuration file contains a few general settings and this is where you can define preset for your images.

Publish `config/twill-image.php` to your app's config folder.

```
php artisan vendor:publish --provider="A17\Twill\Image\TwillImageServiceProvider" --tag=config
```

Usage
-----

[](#usage)

### The `Image` model

[](#the-image-model)

The `Image` model allows you to interact fluently with a media object.

```
$image = new A17\Twill\Image\Models\Image($object, $role, $media);

// or using the Facade
$image = TwillImage::make($object, $role, $media);
```

ArgumentTypeDefaultDescription`$object` (Required)`A17\Twill\Models\Media` `A17\Twill\Models\Block` `object`Your Twill module or block object`$role` (Required)`string``Media` role`$media``A17\Twill\Models\Media``null``Media` instance#### Available methods

[](#available-methods)

Once you have created an instance of the `Image` model, you can interact by using one or chaining many of these methods.

##### `crop`

[](#crop)

You can specify the crop name by passing it as an argument. By default, the `Image` model will look for a crop name `default` and if it isn't availble, it will look for a single crop and select it. If it can't determine the crop, it will result in an error.

```
$image->crop('listing_card');
```

##### `width`

[](#width)

To set the width of the image, you can use this method. The default is an image of 1000 pixels wide. This is useful if you need to display an image with a fixed width or if you know in advance that you will a larger image than the default.

Note: the width is applied to the "fallback" image (``) and to determine the number of image URLs to add to the `srcset` attribute.

```
$image->width(1500);
```

##### `height`

[](#height)

You can set the height of the image with this method. Similar to the `width` method above, it is most useful for fixed-size image. When not used, the height is determined by the aspect ratio of the image and inferred from the width.

```
$image->height(900);

$image->crop('listing')->width(600)->height(400);
```

##### `sources`

[](#sources)

To use mutliples `` elements, you can pass a array to this method by listing the sources other than the main crop. Each item in the array must have a `mediaQuery` and a `crop` key in order to generate the proper `srcset`. You can pass an optional width and height. This is useful when used with the `crop` method to set the main image crop. See also [Art directed images](#art-directed-images).

```
$image->crop('desktop')->sources([
    [
        'mediaQuery' => '(max-width: 400px)', // required
        'crop' => 'mobile', // required
        'width' => 200, // optional
        'height' => 200, // optional
        'srcSetWidths' => [100, 200, 400], // optional
    ],
    [
        'mediaQuery' => '(min-width: 401px) and (max-width: 700px)',
        'crop' => 'tablet',
    ],
]);
```

Media queries can also be generated from a [frontend breakpoints and grid structure](#frontend-breakpoints-and-grid-structure) file by passing a `columns` key instead of `mediaQuery`. You can see the format below.

```
$image->crop('desktop')->sources([
    [
        'columns' => [
            'md' => 'max',
        ],
        'crop' => 'mobile',
    ],
    [
        'columns' => [
            'md' => 'min',
            'lg' => 'max',
        ],
        'crop' => 'tablet',
    ],
]);
```

##### `sizes`

[](#sizes)

Use this method to pass a `sizes` attribute to the model.

```
$image->sizes('(max-width: 400px) 100vw, 50vw');
```

##### `columns`

[](#columns)

As an alternative to the `sizes` method, Twill Image provides a way to generate the `sizes` attribute based on a [frontend breakpoints and grid structure](#frontend-breakpoints-and-grid-structure) file. When placing this JSON file at the base folder of your app, the `sizes` attribute can be generated from passing a series of breakpoints and columns number to this method.

```
$image->columns([
    'xxl' => 6,
    'xl' => 6,
    'lg' => 8,
    'md' => 8,
    'sm' => 8,
    'xs' => 12,
]);
```

This would tell how many columns the image will take at each breakpoint in order to generate to proper `sizes` attribute.

Note: this method will have an effect only when `frontend.config.json` exists at in base folder of your app.

##### `srcSetWidths`

[](#srcsetwidths)

Use this method to give a list a widths to generate the `srcset` attribute. Without this method, Twill Image will auto generate a series of widths based on the image width.

```
$image->srcSetWidths([100, 150, 300, 600, 1200, 2000, 2400, 3600, 5000]);
```

##### `preset`

[](#preset)

With this method you can use an object to pass a value to any of the above methods. You can also add a preset key to the config `config/twill-image.php` and pass the name to this method.

```
// config/twill-image.php

return [
    // ...
    'presets' => [
        'art_directed' => [
            'crop' => 'desktop',
            'width' => 700,
            'sizes' => '(max-width: 767px) 25vw, (min-width: 767px) and (max-width: 1023px) 50vw, 33vw',
            'srcSetWidths' => [350, 700, 1400],
            'sources' => [
                [
                    'crop' => 'mobile',
                    'media_query' => '(max-width: 767px)',
                    'srcSetWidths' => [100, 200, 400],
                ],
                [
                    'crop' => 'tablet',
                    'media_query' => '(min-width: 767px) and (max-width: 1023px)',
                ],
            ],
        ],
    ],
];
```

```
// to use this preset from the config file
$image->preset('art_directed');
```

You can directly pass the full object if you prefer.

```
$image->preset([
    'crop' => 'desktop',
    'width' => 700,
    'sizes' => '(max-width: 767px) 100vw, (min-width: 767px) and (max-width: 1023px) 50vw, 33vw',
    'sources' => [
        [
            'crop' => 'mobile',
            'media_query' => '(max-width: 767px)',
        ],
        [
            'crop' => 'tablet',
            'media_query' => '(min-width: 767px) and (max-width: 1023px)',
        ],
    ],
]);
```

##### `render`

[](#render)

This method will return the rendered view.

```
{{-- resources/views/home.blade.php --}}
@php
$image = TwillImage::make($page, 'preview')->preset('art_directed');
@endphp

{!! $image->render() !!}

{{-- with arguments --}}
{!! $image->render([
    'loading' => 'eager',
]) !!}
```

##### `toArray`

[](#toarray)

If you need to split the image generation from the render (exposing the `Image` model data through a REST API for example), use this method to get all attributes as an array.

```
$previewImage = TwillImage::make($page, 'preview')->preset('art_directed')->toArray();
```

And use the `render` method from the facade to render the view.

```
{{-- resources/views/page.blade.php --}}

{!! TwillImage::render($previewImage) !!}
```

### The facade `render` method

[](#the-facade-render-method)

As seen in the previous section, the image element rendering can be separated from the image attributes generation. You can use the `Image` model to set up your image and pass the resulting object (or its `array` format to the `render` method to output the view).

```
$previewImage = TwillImage::make($page, 'preview')->toArray();
```

```
{!! TwillImage::render($previewImage) !!}
```

or

```

    {!! TwillImage::render($previewImage, [
        'width' => 700,
    ]) !!}

```

#### List of arguments

[](#list-of-arguments)

ArgumentTypeDefaultDescription`class``string`Add class(es) to the wrapper element`imageClass``string`Add class(es) to the img element`height``int``imageSizer``boolean`'auto'Render the image sizer markup if `true`, if set to 'auto', the sizer is rendered when LQIP is set to true`loading``"lazy" | "eager"``lazy`Set native lazy loading attribute`lqip``boolean`See configUse LQIP`sizes``string`The image sizes attributes`imageStyles``array``[]`Apply styles to placeholder and main `img` tags (ex.: `[['object-fit' => 'contain']]`#### Examples

[](#examples)

```
{!! TwillImage::make($item, 'preview_image')->sizes('(max-width: 767px) 50vw, 100vw')->render(); !!}

@php
$heroImage = TwillImage::make($item, 'preview_image');
$listingImage = TwillImage::make($item, 'preview_image')->crop('listing');
@endphp

{!! TwillImage::render($heroImage) !!}

{!! TwillImage::render($listingImage) !!}
```

Configuration
-------------

[](#configuration)

In `config/twill-image.php`, you can define general options and image presets. A preset informs the `Image::preset` method which crop to output along other options like responsive sources.

```
