Skip to content

Instantly share code, notes, and snippets.

@samnabi
Created February 1, 2016 18:41
Show Gist options
  • Star 14 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save samnabi/f4ecb351f2ec2bd596e5 to your computer and use it in GitHub Desktop.
Save samnabi/f4ecb351f2ec2bd596e5 to your computer and use it in GitHub Desktop.
Kirby v2: Shrink large images on upload
<?php
// Copy this code into your config.php file
// Replace the default $maxDimension to meet your needs
// Read more about Kirby's Panel hooks at https://getkirby.com/docs/panel/developers/hooks
// Shrink large images on upload
kirby()->hook('panel.file.upload', 'shrinkImage');
kirby()->hook('panel.file.replace', 'shrinkImage');
function shrinkImage($file, $maxDimension = 1000) {
try {
if ($file->type() == 'image' and ($file->width() > $maxDimension or $file->height() > $maxDimension)) {
// Get original file path
$originalPath = $file->dir().'/'.$file->filename();
// Create a thumb and get its path
$resized = $file->resize($maxDimension,$maxDimension);
$resizedPath = $resized->dir().'/'.$resized->filename();
// Replace the original file with the resized one
copy($resizedPath, $originalPath);
unlink($resizedPath);
}
} catch(Exception $e) {
return response::error($e->getMessage());
}
}
?>
@carstengrimm
Copy link

just tried that one, however it does not resize anything :(

@organised
Copy link

I know this was posted a while ago, but it worked a treat! thanks for this!

@mschuetze
Copy link

Doesn´t work for me.
Files with height/width higher than the maxValue won´t be uploaded. They don´t show up in the files panel. No error message.
Files below the maxDimension get uploaded without problems.

Do I need a plugin for this to work? Or is it just the hook?

@illycz
Copy link

illycz commented Mar 2, 2018

@samnabi in replace hook there must be another variable.

Changing line 10 solves the problem:
function shrinkImage($file, $oldFile, $maxDimension = 1000) {

@qwertzuiop13
Copy link

How to keep the two images ? The original and the thumb, with different name ?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment