Hook to resize images to a power of two

Hey all :wave:

I’m currently developing a site based on react three fiber. Since three.js requires textures to follow the power of two rule and since I don’t want to force the client to adjust all images manually I thougth about writing a little file.create:after hook (my first hook by the way, so I’m unfortunately quite inexperienced).

The goal is to:

  1. Save the original aspect ratio in a hidden field for further use
  2. Resize the image to a power of two of 512×1024px (e.g. for portrait images)

The problem I have is, that everything I tried so far keeps the aspect ratio of the image. Which makes total sense, of course, because that’s the desired behavior in let’s say 99% of cases :sweat_smile:

Here’s what I currently have (derived from kirby autoresize plugin):


function powerOfTwo($file) {
    if($file->isResizable()) {
      if ($file->width() < $file->height()) {
        try {
          kirby()->thumb($file->root(), $file->root(), [
            'width'   => 512,
            'height'  => 1024
        catch (Exception $e) {
          throw new Exception($e->getMessage());

This text will be hidden
', [
	'hooks' => [
		'file.create:after' => function ($file) {
        'aspect' => $file->height() / $file->width()
		'file.replace:after' => function ($newFile, $oldFile) {

I thought thumb() could be a way to achieve resizing images to a power of two, since I couldn’t find anywhere that thumb() always keeps the aspect ratio (as it’s explicitely stated in the docs for example for resize()).

Any ideas how to achieve that? Happy about any hint! :pray:

Thumb works like resize if you don’t set crop to true, or the shorthand $file->crop(512,1024).

@texnixe Thanks for your super fast reply! :star_struck:

Thumb works like resize if you don’t set crop to true

Okay, good to know! I already tried using crop but as the name suggests, it crops the image which unfortunately is not an option.

Maybe it’s easier to show what I’m trying to accomplish than to try to put it into words:

Ok, I see, this kind of image modification is not natively supported by Kirby.

Looks as if you can use ImageMagic mogrify for this purpose: ImageMagick - Command-line Tools: Mogrify

Which would require that your server has ImageMagic enabled and you need a custom thumb driver or call that command directly via exec().

Looks as if you can use ImageMagic mogrify for this purpose

Cool, thanks for pointing! I’ll give that a try and report back if I got it working

Nice! :heart_eyes: :star_struck: :pray: