Craft provides the very nice TWIG function dataUrl(pathToImg) to inline images in e-mails.


<img src="{{ dataUrl('@webroot/assets/img/logo.svg')" />

will base64 encode the image into the src. This also works if you pass in an instance of an asset:

{% set myAsset = craft.assets.id(123).one() %}
<img src="{{ dataUrl(myAsset) }}" />

My question: Does anyone know how to resize the image first, if you pass in an asset?

This does not work:

<img src="{{ dataUrl(myAsset.getUrl({width: 200, height: 200})) }}" />

Found it, this works:

<img src="{{ dataUrl('@webroot' ~ myAsset.getUrl({width: 200, height: 200}, true)) }}" />

Two important things:

  • prepend the @webroot alias to the myAsset.getUrl(...)
  • set the second parameter of getUrl(...) to true: myAsset.getUrl({...}, true). This ensures that a real file path is returned by getUrl, because the image is transformed immediately on call. This is necessary for the dataUrl function to work. If it is not present, Craft might return a URL pointing to the image transformation controller (which transforms when called for the first time, this might go wrong here).

One method that comes to my mind is to create an asset configuration in admin panel (Settings -> Assets), where you can create different Image Transform configurations.

For example, I can create an Image Transforms called Thumbnail then set the required dimensions and quality of the image.

Once you create an Image Transforms, you can utilize them with twig template:

  • Thanks, but the question was how to get a resized image into dataUrl(...) – Matthias Redl-Mann Apr 22 at 11:40
  • @MatthiasRedl-Mann My apologies - I think I've misunderstood the question – Will Kim Apr 22 at 14:44
  • No worries, good that you tried! – Matthias Redl-Mann Apr 22 at 15:32

You can use Asset::setTransform or Asset::copyWithTransform to get (a copy) of the asset object with your transform applied. Then you can pass that into dataUrl().

{# Apply the transform to myAsset directly #}
{% do myAsset.setTransform({width: 200, height: 200}) %}
{{ dataUrl(myAsset)  }}

{# Use this if you need myAsset without the transform later #}
{% set thumb = myAsset.copyWithTransform({width: 200, height: 200}) %}
{{ dataUrl(thumb)  }}
  • how would I call the static methods from TWIG? – Matthias Redl-Mann Apr 22 at 11:59
  • @Matthias Redl-Mann Sorry for the confusion, they're not static methods, that's just a code notation convention. You can call the methods like any other instance method using dot-notation. I updated the code example with working examples for both methods, either of them should work correctly now. – MoritzLost Apr 23 at 14:47
  • Looks good, I will try! – Matthias Redl-Mann Apr 23 at 15:44

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.