How to use the new asset class to generate thumbnails

Via Kirby 2.3’s changelog:

New Asset class, which can now convert any external files/images into Kirby file objects and make them resizable with the thumb api.

I don’t believe there’s an example of this in the docs, and I can’t quite figure it out looking at Kirby’s core. I’m familiar with creating new media objects for files within assets (described here), but generating thumbnails from those media objects wasn’t implemented as of the 2.3 beta. Now that external images can be converted into file objects it sounds like generating thumbs from assets should be possible.

Here’s my current code. Getting the image’s ratio, height, etc. works, but attempting to get the url for a thumbnail with either method just returns the original image’s location within assets. No thumb is generated.

<?php
  $image = new Media (kirby()->roots()->index() . '/assets/images/hero-default.jpg', $site->url() . "/assets/images/hero-default.jpg");
  echo $image->ratio();
  echo $image->resize(1500)->url();
  echo thumb($image, array('width' => 1500))->url();
?>

As the change log says, there is a new class for that, called Asset. Its only difference to Media is that it supports thumbnails. Media itself can’t really support that as the thumb component is not part of the Toolkit while the Media class is.

So you can use the following code:

<?php
  $image = new Asset('assets/images/hero-default.jpg');
  echo $image->ratio();
  echo $image->resize(1500)->url();
  echo thumb($image, array('width' => 1500))->url();
1 Like

Ah, that makes sense. The Asset path syntax seems to be a little different from the Media syntax described here, however. Below is the code that ended up working for me. Thank you for your help, @lukasbestle.

<?php
  $image = new Asset('/assets/images/hero-default.jpg', $kirby->urls()->assets() . '/images/hero-default.jpg');
  echo $image->resize(1500)->url();
?>

Ah, yes. Thank you for correcting. Actually it’s even a bit simpler:

<?php
  $image = new Asset('assets/images/hero-default.jpg');
  echo $image->resize(1500)->url();
?>

You don’t need to pass the second param at all. :slight_smile:

Even better, thanks!