Skip to content

Instantly share code, notes, and snippets.

@samnabi
Created February 1, 2016 18:41
Show Gist options
  • 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());
}
}
?>
@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