Replace image after converting it in a Hook

Hello,

I have a question that’s probably asked several times, but I don’t find the right keywords for my search.

I created a hook that converts an uploaded HEIC image into a JPG using Imagick. But in my panel, still the heic image is present and not the jpg - I manually have to go to “Select”, deselect the heic and select the jpg.

How can I swap the two files automatically within the hook? Or do I have a wrong understanding how to accomplish this?

Here’s my code so far:

return [
    'hooks' => [
        'file.create:after' => function (Kirby\Cms\File $file) {
            $ext = strtolower($file->extension());
            if($ext == 'heic' || $ext == 'heif') 
            {
                $source = $file->root();
                $targetName = $file->name() . '.jpg';
                $targetPath = $file->parent()->root() . '/' . $targetName;

                $img = new Imagick($source);

                $img->autoOrient();
                // $img->resizeImage(2048, 2048, Imagick::FILTER_LANCZOS, 1, true);
                $img->setImageFormat('jpeg');
                $img->setImageCompressionQuality(90);
                $img->writeImage($targetPath);

                $img->clear();
                $img->destroy();
                // unlink($source);

                // swap images in gallery:
                // *todo*
            }
        }
    ]
]

Thanks and all the best!

Welcome to the community :slight_smile:

You can possible do it with `update()` to set a new value for the field. You can also deelte the heic file as well.

I think the best way is actually to register the heic format and then you can use kirby image manipulation without jumping throught hoops in a hook to do it.

That way you can use thumb() in your templates and snippets and set the format option to jpeg

Thank you very much for your answer and the warm welcome!

I now tried with a basic plugin to register the file type and also played with thumbnails and the update-function.

Unfortunately, I didn’t get it to work. I think I just keep taking care that - when uploading images from iPhone directly in the Panel - I set the options in iOS to ‘most compatible’.

For a really nice user experience, the images should be converted before uploading, I guess?