Craft 3 Documentation

Image Transforms

Rather than requiring that everyone upload images at a certain size, Craft lets you define “image transforms”, which set those rules on Craft’s end instead. Transforms are non-destructive, meaning that they have no effect on the original image that was uploaded.

Defining Transforms from the Control Panel #

You can define transforms from the Control Panel by going to Settings → Assets → Image Transforms and clicking the “New Transform” button.

Each transform has the following settings:

Mode can be set to the following values:

If Mode is set to “Crop”, an additional “Crop Position” setting will appear, where you can define which area of the image should be treated as the focal point when cropping. Its options include:

If you leave either Width or Height blank, that dimension will be set to whatever maintains the image’s aspect ratio. So for example, if you have an image that is 600 by 400 pixels, and you set a transform’s Width to 60, but leave Height blank, the resulting height will be 40.

If you leave Quality blank, Craft will use the quality set by your defaultImageQuality config setting.

Image Format can be set to the following values:

If you leave Image Format blank, Craft will use the original image’s format if it’s web-safe (.jpg, .png, or .gif); otherwise it will try to figure out the best-suited image format for the job. If it can’t determine that (probably because ImageMagik isn’t installed), it will just go with .jpg.

Applying CP-defined Transforms to Images #

To output an image with a transform applied, simply pass your transform’s handle into your AssetFile Model’s getUrl(), getWidth(), and getHeight() functions:

<img src="{{ asset.getUrl('thumb') }}" width="{{ asset.getWidth('thumb') }}" height="{{ asset.getHeight('thumb') }}">

Defining Transforms in your Templates #

You can also define transforms directly in your templates.

First, you must create an object that defines the transform’s parameters:

{% set thumb = {
    mode: 'crop',
    width: 100,
    height: 100,
    quality: 75,
    position: 'top-center'
} %}

Then you can pass that object into your AssetFileModel’s getUrl(), getWidth(), and getHeight() functions:

<img src="{{ asset.getUrl(thumb) }}" width="{{ asset.getWidth(thumb) }}" height="{{ asset.getHeight(thumb) }}">

Note how in that example there are no quotes around “thumb”, like there were in the first one. That’s because in the first one, we were passing a string set to a CP-defined transform’s handle, whereas in this example we’re passing a variable referencing the ‘thumb’ object we created within the template.

Possible Values #

All of the same settings available to CP-defined transforms are also available to template-defined transforms.