Override `image` Kirby Tag for Resizing

I’m trying to override the image kirby tag to include a conditional that will resize the image if it is larger than 600px. I followed a similar approach to this one and created /site/tags/image.php. It’s an exact copy of the image part of /kirby/extensions/tags.php, with the added condition I’ve tried a few different ways:

    'html' => function($tag) {

      $url     = $tag->attr('image');
      $alt     = $tag->attr('alt');
      $title   = $tag->attr('title');
      $link    = $tag->attr('link');
      $caption = $tag->attr('caption');
      $file    = $tag->file($url);

      // added conditional: resize image if wider than 600px
      if($file) {
        if($file->width() > 600) {
          // $file = thumb($file, array('width' => 600), true);
          // $file = $file->thumb(['width' => 600]);
          $file = $file->width(600);
      // end of added conditional

      // use the file url if available and otherwise the given url
      $url = $file ? $file->url() : url($url);

Each of my three attempts result in an error:

Method Kirbytext::__toString() must not throw an exception, caught Error: Call to undefined method Asset::alt()

Any ideas? Thanks in advance!

Use a hook and do it on file upload like Image Shrink does. Or just use Image Shrink :slight_smile:

You can add this after if($file):

if($file) {

      if($file->width() > 600) {
        if($thumb = $file->resize(600)) {
          $url = $thumb->url();

But note that this will then output all images added via the Kirbytag reduced to a size of 600px. Is this really what you want?

Shrinking images on upload might be an alternative, but not if you only want to resize images added via Kirbytag while preserving the original files.

1 Like

You can add an extra option to the tag cant you? so you can set an arbitary size on the tag rather then hard coding it at 600. I am not sure what happens if you set a size larger then the images physical dimensions though.

Well, yes, of course. you can set an attribute. It depends on what you want to achieve.

Kirby does not upsize images unless you specifically set the upscale option when using the thumbs method.

So the main question here is: What is the use case?

Personally, I like to use the image shrink plugin in combination with template code and tags because my clients have a habit of uploading 5 million pixel wide photos straight from a digital camera. Image shrink brings them down to something more sensible like 2,000px wide, and I go from there.

That works! Thanks!

Yeah, for my use case, I want to always preserve the original image so down the road, I can always format the image differently later on.